package com.platform.qujia.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.platform.qujia.constantEnum.DecimalConstant;
import com.platform.qujia.dao.*;
import com.platform.qujia.enums.ElectronCardType;
import com.platform.qujia.enums.WxTemplateEnum;
import com.platform.qujia.param.request.RechargeBalance;
import com.platform.qujia.pojo.*;
import com.platform.qujia.pojo.dto.ElectronicCardSubRes;
import com.platform.qujia.pojo.vo.RechargePrivilegeVO;
import com.platform.qujia.rocketmq.SettleInfoProducer;
import com.platform.qujia.pojo.vo.ElectronicCardTypeListVO;
import com.platform.qujia.pojo.vo.ElectronicCardListVO;
import com.platform.qujia.service.*;
import com.platform.qujia.utils.*;
import com.platform.qujia.utils.exception.CustomException;
import com.platform.qujia.utils.jinkong.JKPayParam;
import com.platform.qujia.utils.jinkong.JKPayUtil;
import com.platform.qujia.utils.sxfpay.SXFPayParam;
import com.platform.qujia.utils.sxfpay.SXFPayUtil;
import com.platform.qujia.utils.tonglianpay.SybConstants;
import com.platform.qujia.utils.tonglianpay.SybUtil;
import com.platform.qujia.utils.tonglianpay.TLPayParam;
import com.platform.qujia.utils.tonglianpay.TLPayUtil;
import com.platform.qujia.utils.tonglianpay.tlfusclasspay.TLFusClassPayUtil;
import com.platform.qujia.utils.tonglianpay.tlfusclasspay.struct.body.TLFusClassPayParam;
import com.platform.qujia.utils.tonglianpay.tlfusclasspay.util.SignUtils;
import com.platform.qujia.utils.weixinapp.WxPushUtil;
import com.platform.qujia.utils.weixinapp.WxTemplateData;
import com.platform.qujia.utils.weixinapp.WxTemplateMsg;
import com.platform.qujia.utils.yunHua.YunHuaParam;
import com.platform.qujia.utils.yunHua.yunHuaPayUtils;
import com.platform.qujia.utils.yunpay.SBPayParam;
import com.platform.qujia.utils.yunpay.SBPayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.asm.Advice.This;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/*+
 * <Title> ElectronicMembershipCardController </Title>
 * <Description> 电子会员卡（储蓄卡）功能模块 </Description>
 * @Date 2021年3月22日
 */
//@QuJiaRequest()
@CrossOrigin
@Api(tags = "电子会员卡（储蓄卡）功能")
@RestController
@Slf4j
public class ElectronicMembershipCardController {
    private static Logger logger =(Logger) LoggerFactory.getLogger(ElectronicMembershipCardController.class);

    @Resource
    private ElectronicMembershipCardService electronicMembershipCardService;
    @Resource
    private GzhNewsTemplateService gzhNewsTemplateService;
    @Resource
    private WxPushUtil wxPushUtil;
    @Resource
    private PayOrderService payOrderService;
    @Resource
    private IntegralRuleService integralRuleService;
    @Resource
    private SysDictDataService sysDictDataService;
    @Resource
    private AppUserInfoService appUserInfoService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Resource
    private ReductionActivityService reductionActivityService;
    @Resource
    private CouponService couponService;
    @Resource
    private PayOrderMapper payOrderMapper;
    @Resource
    private ReductionActivityBalanceRecordService reductionActivityBalanceRecordService;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${qujia.domainName}")
    private String domainName;

    @Value("${qujia.private_pfxPath}")
    private String private_pfxPath;

    @Value("${qujia.public_certPath}")
    private String public_certPath;

    @Value("${qujia.yunhuaPrePayUrl}")
    private String yunHuaPrePayUrl;
    @Autowired
    private StationMapper stationMapper;
    @Autowired
    private CustomerCardSettingMapper customerCardSettingMapper;

    @Resource
    private SettleInfoProducer settleInfoProducer;
    @Resource
    private CouponController couponController;
    @Autowired
    private CustomerCardSettingDetailService customerCardSettingDetailService;

    @Autowired
    private PresentAmountRecordService presentAmountRecordService;

    @Autowired
    private PhysicalCardService physicalCardService;
    @Autowired
    private CustomerCardUseRecordMapper customerCardUseRecordMapper;
    @Autowired
    private ElectronicMembershipCardMapper electronicMembershipCardMapper;



//        String private_pfxPath="C:\\Users\\zcs\\Desktop\\商户密钥\\私钥.pfx"; //商户私钥地址
//
//    String public_certPath="C:\\Users\\zcs\\Desktop\\商户密钥\\xdzf_cfca_prd.cer"; //现代支付公钥地址


    //查询该油站是否启用电子会员卡
    @RequestMapping(value = "/getStationCardEnabledFlag", method = RequestMethod.GET)
    @ResponseBody
    public String getStationCardEnabledFlag(@RequestParam Integer enterpriseId){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(enterpriseId !=null){
            resultData = ResultData.success(enterpriseService.selectEnterpriseInfo(enterpriseId).getCardFlag());
        }else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll);
        }
        return gson.toJson(resultData);
    }

    //获取用户电子会员卡（储蓄卡）列表
    @RequestMapping(value = "/getElectronicCardList", method = RequestMethod.GET)
    @ApiOperation(value = "获取用户电子会员卡（储蓄卡）列表", httpMethod = "GET", notes = "获取用户电子会员卡（储蓄卡）列表")
    @Transactional
    public ResultData<ElectronicCardListVO> getElectronicCardList(@ApiParam(value = "油企ID", required = true) @RequestParam Integer enterpriseId,
                                        @ApiParam(value = "用户手机号", required = true) @RequestParam String mobilePhone){
        //返回结果集
        ResultData<ElectronicCardListVO> resultData = null;
        logger.info("获取用户电子会员卡信息参数：油企ID："+ enterpriseId+"; 用户mobilePhone："+ mobilePhone);
        if(null !=enterpriseId && StringUtils.isNotBlank(mobilePhone)){

            Enterprise enterprise = enterpriseService.selectEnterpriseInfo(enterpriseId);
            boolean cardUseForAll = StringUtils.equals("1",enterprise.getCardUseRangeFlag());

            //查询会员卡规则
            CustomerCardSetting cardSetting = customerCardSettingMapper.getOne(CustomerCardSetting.builder().stationId(enterpriseId).delFlag("0").build());
            //开启的电子卡
            String[] split = null;
            if(cardSetting !=null && StringUtils.isNotBlank(cardSetting.getCardOilsType())){
                split = cardSetting.getCardOilsType().split(",");
            } else {
                throw new CustomException("油企未开启电子卡设置");
            }


            ElectronicCardListVO vo = new ElectronicCardListVO();
            vo.setCardUseRangeFlag(enterprise.getCardUseRangeFlag());
            //创建会员卡
            AppUserInfo appUserInfo = appUserInfoService.getAppUserInfo(AppUserInfo.builder().mobilePhone(mobilePhone).stationId(enterpriseId).build());
            if(appUserInfo !=null){
                if (!cardUseForAll) {
                    // 单站使用时查询列表
                    Station station = new Station();
                    station.setEnterpriseId(enterpriseId);
                    station.setDeleteStatus("0");
                    station.setStatus("1");
                    List<Station> stations = stationMapper.queryStationList(station);
                    List<CustomerElectronicCard> cardList = new ArrayList<>();
                    for (Station station1 : stations) {
                        List<CustomerElectronicCard> cards = queryAndCreateCard(appUserInfo, split, enterprise, station1);
                        cardList.addAll(cards);
                    }
                    List<ElectronicCardTypeListVO> cardTypeList = new ArrayList<>();
                    Map<String,ElectronicCardTypeListVO> typeMap = new HashMap<>();
                    for (CustomerElectronicCard card : cardList) {
                        String cardType = card.getCardOilsType();
                        ElectronicCardTypeListVO vo1 = typeMap.get(cardType);
                        if (vo1 == null) {
                            vo1 = new ElectronicCardTypeListVO();
                            vo1.setCardList(new ArrayList<>());
                            vo1.setCardOilsType(cardType);
                            vo1.setTotalAmt(BigDecimal.ZERO);
                            typeMap.put(cardType,vo1);
                            cardTypeList.add(vo1);
                        }
                        List<CustomerElectronicCard> list1 = vo1.getCardList();
                        list1.add(card);
                        vo1.setTotalAmt(vo1.getTotalAmt().add(card.getTotalAmt()));
                    }
                    // 油站名和 在 ReturnCashCardList 的下标值
                    Map<String,Integer> map = new HashMap<>();
                    int index = -1;
                    for (ElectronicCardTypeListVO item : cardTypeList) {
                        for (CustomerElectronicCard customerElectronicCard : item.getCardList()) {
                            if (customerElectronicCard.getReturnCashAmt().compareTo(BigDecimal.ZERO) > 0) {
                                if (map.containsKey(customerElectronicCard.getStationName())){
                                    for (int i = 0; i < vo.getReturnCashCardList().size(); i++) {
                                        if (vo.getReturnCashCardList().get(i).getStationName().equals(customerElectronicCard.getStationName())){
                                            index = i;
                                        }
                                    }
                                    if (index >= 0) {
                                        vo.getReturnCashCardList().remove(index);
                                        index = -1;
                                    }
                                    vo.getReturnCashCardList().add(customerElectronicCard);
                                    map.put(customerElectronicCard.getStationName(),vo.getReturnCashCardList().size());
                                } else {
                                    vo.getReturnCashCardList().add(customerElectronicCard);
                                    map.put(customerElectronicCard.getStationName(),vo.getReturnCashCardList().size());
                                }
                            }
                            if (!map.containsKey(customerElectronicCard.getStationName())){
                                vo.getReturnCashCardList().add(customerElectronicCard);
                                map.put(customerElectronicCard.getStationName(),vo.getReturnCashCardList().size());
                            }
                        }
                    }
                    vo.setCardTypeList(cardTypeList);
                } else {
                    // 多站通用时查询列表
                    vo.setCardList(queryAndCreateCard(appUserInfo,split,enterprise,null));
                }
                // 查询储值卡列表
                vo.setPhysicalCardList(getPhysicalCard(appUserInfo));
                resultData = ResultData.success(vo);
            }
        }else {
            resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return resultData;
    }

    // 查询会员绑定的储值卡
    private List<PhysicalCard> getPhysicalCard(AppUserInfo appUserInfo){
        Integer appUserId = appUserInfo.getUserId();
        PhysicalCard physicalCard = new PhysicalCard();
        physicalCard.setAppUserId(appUserId);
        return physicalCardService.selectByPhysicalCardList(physicalCard);
    }


    private List<CustomerElectronicCard> queryAndCreateCard(AppUserInfo userInfo,String[] cardTypes,Enterprise enterprise,Station station){
        boolean cardUseForAll = StringUtils.equals("1",enterprise.getCardUseRangeFlag());
        List<CustomerElectronicCard> list;
        if (cardUseForAll) {
            list = electronicMembershipCardService.getCustomerElectronicCardListForEnterprise(userInfo.getMobilePhone(), cardTypes, enterprise.getEnterpriseId());
        }else{
            list = electronicMembershipCardService.getCustomerElectronicCardListForStation(userInfo.getMobilePhone(), cardTypes, station.getStationId());
        }
        for (String cardType : cardTypes) {
            // 查询这个type的电子卡有没有
            long count = list.stream().filter(c -> StringUtils.equals(cardType,c.getCardOilsType())).count();
            if (count == 0) {
                // 没有这个type的电子卡则创建
                CustomerElectronicCard.CustomerElectronicCardBuilder builder = CustomerElectronicCard.builder()
                        .amt(BigDecimal.ZERO)
                        .customerNo(userInfo.getMemberCode())
                        .cardOilsType(cardType)
                        .createTime(new Date())
                        .returnCashAmt(BigDecimal.ZERO)
                        .mobilePhone(userInfo.getMobilePhone());
                if (cardUseForAll) {
                    builder.stationId(enterprise.getEnterpriseId());
                }else{
                    builder.stationId2(station.getStationId());
                    builder.stationName(station.getStationName());
                }
                CustomerElectronicCard newCard = builder.build();
                electronicMembershipCardService.insetElectronicCard(newCard);
                list.add(newCard);
            }
        }
        return list;
    }

    //客户电子会员卡表操作
/*    public void createCustomerElectronicCard(AppUserInfo request, String[] split){
        //split 电子卡的列表[1, 2, 3]
        if(split !=null && split.length >0){
            for(int i=0; i<split.length; i++){
                String cardOilsType = String.valueOf(split[i]);
                List<CustomerElectronicCard> electronicCardList = electronicMembershipCardService.getElectronicCardList(
                        CustomerElectronicCard.builder().cardOilsType(cardOilsType).mobilePhone(request.getMobilePhone()).stationId(request.getStationId()).build());
                if(null != electronicCardList  && electronicCardList.size() ==1){
                    electronicMembershipCardService.updateElectronicCardInfoByPhone(CustomerElectronicCard.builder()
                            .stationId(request.getStationId())
                            .mobilePhone(request.getMobilePhone())
                            .cardOilsType(cardOilsType).build());
                }else {
                    electronicMembershipCardService.insetElectronicCard(CustomerElectronicCard.builder()
                            .stationId(request.getStationId())
                            .amt(BigDecimal.ZERO)
                            .customerNo(request.getMemberCode())
                            .cardOilsType(cardOilsType)
                            .createTime(new Date())
                            .mobilePhone(request.getMobilePhone()).build());
                }
            }
        }
    }*/

    //用户充值电子会员卡（储蓄卡）生成充值记录
    @Transactional
    @PostMapping("/rechargeBalance")
    @ApiOperation(value = "用户充值电子会员卡（储蓄卡）生成充值记录")
    public ResultData<String> rechargeBalance(@RequestBody RechargeBalance rechargeBalance){
        logger.info("充值卡类型："+ rechargeBalance.getCardOilsType() + "; 充值金额："+ rechargeBalance.getAmt() +"; 油站ID："+ rechargeBalance.getStationId() + "; 充值手机号："+rechargeBalance.getMobilePhone());
        //Gson gson =new Gson();
        //返回结果集
        ResultData<String> resultData = null;
        if((rechargeBalance.getStationId() !=null || rechargeBalance.getEnterpriseId() != null ) && StringUtils.isNotBlank(rechargeBalance.getCardOilsType()) && StringUtils.isNotBlank(rechargeBalance.getMobilePhone())){
            //获取用户信息

            Station station = enterpriseService.selectStationById(rechargeBalance.getStationId());
            if (station==null) {
                throw new CustomException("油站未找到");
            }
            if (!StringUtils.equals("1", station.getEnterprise().getCardFlag())) {
                throw new CustomException("油企未开启电子卡");
            }

                AppUserInfo appUserInfoResult = appUserInfoService.getAppUserInfo(AppUserInfo.builder().stationId(station.getEnterpriseId()).mobilePhone(rechargeBalance.getMobilePhone()).build());
                if(null != appUserInfoResult){
                    //要充值电子卡的规则
//                    List<CustomerCardSetting> cardRechargeSettingList = electronicMembershipCardService.getCardRechargeSettingList(
//                            CustomerCardSetting.builder()
//                                    .orderBy("DESC")
//                                    .cardOilsType(rechargeBalance.getCardOilsType())    //卡类型
//                                    .stationId(station.getEnterpriseId())               //油企ID
//                                    .build());

                    List<CustomerCardSetting> cardRechargeSettingList = electronicMembershipCardService.getCardRechargeMinAmt(
                            CustomerCardSetting.builder()
                                    .stationId(station.getEnterpriseId())  //油企ID
                                    .build());
                    if (cardRechargeSettingList == null || cardRechargeSettingList.size() == 0) {
                        throw new CustomException("油企未开启电子卡");
                    }

                    CustomerCardSetting cardSetting = cardRechargeSettingList.get(0);
                    if (!StringUtils.contains(cardSetting.getCardOilsType(), rechargeBalance.getCardOilsType())) {
                        throw new CustomException("油企未启用"+ ElectronCardType.getByKey(rechargeBalance.getCardOilsType(),ElectronCardType.GAS).getName() +"卡");
                    }

//                    if(cardRechargeSettingList.size() != 0 && cardRechargeSettingList.get(0) != null && cardRechargeSettingList.get(0).getCustomerCardSettingDetailList() != null && cardRechargeSettingList.get(0).getCustomerCardSettingDetailList().size() != 0){
//                        List<CustomerCardSettingDetail> a = cardRechargeSettingList.get(0).getCustomerCardSettingDetailList().stream().filter(s-> "0".equals(s.getDelFlag())).collect((Collectors.toList()));
//                        cardRechargeSettingList.get(0).setCustomerCardSettingDetailList(a);
//                    }
                    //汽油卡最低金额
                    if(cardRechargeSettingList !=null&&cardRechargeSettingList.size()>0&&rechargeBalance.getCardOilsType().equals("1")&&cardRechargeSettingList.get(0).getGasolineMinAmt()!=null){
                        if(cardRechargeSettingList.get(0).getGasolineMinAmt().compareTo(new BigDecimal( rechargeBalance.getAmt()))>0){
                            return ResultData.error( "不满足最低充值金额");
                        }
                    }
                    //柴油卡最低金额
                    if(cardRechargeSettingList !=null&&cardRechargeSettingList.size()>0&&rechargeBalance.getCardOilsType().equals("2")&&cardRechargeSettingList.get(0).getDieselMinAmt()!=null){
                        if(cardRechargeSettingList.get(0).getDieselMinAmt().compareTo(new BigDecimal( rechargeBalance.getAmt()))>0){
                            return ResultData.error( "不满足最低充值金额");
                        }
                    }

                    //LNG卡最低金额
                    if(cardRechargeSettingList !=null&&cardRechargeSettingList.size()>0&&rechargeBalance.getCardOilsType().equals("3")&&cardRechargeSettingList.get(0).getLNGMinAmt()!=null){
                        if(cardRechargeSettingList.get(0).getLNGMinAmt().compareTo(new BigDecimal( rechargeBalance.getAmt()))>0){
                            return ResultData.error( "不满足最低充值金额");
                        }
                    }

                    //CNG卡最低金额
                    if(cardRechargeSettingList !=null&&cardRechargeSettingList.size()>0&&rechargeBalance.getCardOilsType().equals("4")&&cardRechargeSettingList.get(0).getCNGMinAmt()!=null){
                        if(cardRechargeSettingList.get(0).getCNGMinAmt().compareTo(new BigDecimal( rechargeBalance.getAmt()))>0){
                            return ResultData.error( "不满足最低充值金额");
                        }
                    }
                    //通用卡最低金额
                    if(cardRechargeSettingList !=null&&cardRechargeSettingList.size()>0&&rechargeBalance.getCardOilsType().equals("0")&&cardRechargeSettingList.get(0).getGenericMinAmt()!=null){
                        if(cardRechargeSettingList.get(0).getGenericMinAmt().compareTo(new BigDecimal( rechargeBalance.getAmt()))>0){
                            return ResultData.error( "不满足最低充值金额");
                        }
                    }
                    //计算优惠
                    rechargeBalance.setEnterpriseId(station.getEnterpriseId());
                    CalPresentAmt calPresentAmt = this.calPresentAmt(cardRechargeSettingList, rechargeBalance.getCardOilsType(), new BigDecimal(rechargeBalance.getAmt()), rechargeBalance,"wx",true);

                    BigDecimal presentAmt =calPresentAmt.getPresentAmt();
                    logger.info("总共赠送：" + presentAmt);
                    //查询客户该卡类型的余额
                    CustomerElectronicCard electronicCardInfoByPhone = electronicMembershipCardService.getAndCreateCustomerElectronicCard(appUserInfoResult, rechargeBalance.getCardOilsType(), station);

                    BigDecimal balance =BigDecimal.ZERO;
                    //该客户要充值会员卡之前的余额
                    if(null != electronicCardInfoByPhone)
                        balance = electronicCardInfoByPhone.getTotalAmt();

                    //生成充值记录
                    String orderNo = System.currentTimeMillis() + RandomStringUtils.randomNumeric(6);    //订单号 时间+6位随机数
                    electronicMembershipCardService.insetCardUseRecordRecharge(CustomerCardUseRecord.builder()
                            .orderOriginType(rechargeBalance.getOrderOriginType())
                            .amt(new BigDecimal(rechargeBalance.getAmt()))
                            .presentAmt(presentAmt)
                            .customerNo(appUserInfoResult.getMemberCode())
                            .stationId(rechargeBalance.getStationId())
                            .mobilePhone(rechargeBalance.getMobilePhone())
                            .cardOilsType(rechargeBalance.getCardOilsType())
                            .orderNo(orderNo)
                            .balance(balance)
                            .usageType("+")
                            .status("0")
                            .enterpriseId(station.getEnterpriseId())
                            .enterpriseName(station.getEnterprise().getEnterpriseName())
                            .createTime(new Date())
                            .ccsdId(calPresentAmt.getCcsdId())
                            .operator(rechargeBalance.getOperator())
                            .build());
                   /* //判断
                    reductionActivityBalanceRecordService.createBalanceRecord(rechargeBalance,station,appUserInfoResult);*/
                    logger.info( rechargeBalance.getMobilePhone() + " 电子卡的充值单号：" +orderNo);
                    resultData = ResultData.success(orderNo);
                }else {
                    resultData = ResultData.error(CodeMsg.USER_NOT_EXSIST);
                }
        }else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll);
        }
        return resultData;
    }

    /*    public CouponInfoSettingDetail getCouponInfoIdByCardSetting(List<CustomerCardSetting> cardRechargeSettingList,String cardOilsType, BigDecimal amt,RechargeBalance rechargeBalance) {
    CouponInfoSettingDetail couponInfoSettingDetail=new CouponInfoSettingDetail();
    if(cardRechargeSettingList==null||cardRechargeSettingList.size()==0){
        return null;
    }
    CustomerCardSetting customerCardSetting = cardRechargeSettingList.get(0);
    CustomerCardSettingDetail form = new CustomerCardSettingDetail();
    //form.setParentId(cardSetting.getId());
    form.setActivityType(CustomerCardSettingDetail.ACTIVITYTYPE_COUPON);
    form.setDelFlag("0");
    form.setCardType(cardOilsType);
    form.setEnterpriseId(rechargeBalance.getEnterpriseId().longValue());
    form.setStationId(rechargeBalance.getStationId().longValue());
    form.setStatus("NORMAL");

    List<CustomerCardSettingDetail> customerCardSettingDetails = electronicMembershipCardService.selectCardSettingDetail(form);
    for (CustomerCardSettingDetail cardDetail : customerCardSettingDetails) {
        CustomerCardSettingDetailContent contentQuery=new CustomerCardSettingDetailContent();
        contentQuery.setCcsdId(cardDetail.getCardSettingDetailId().longValue());
        List<CustomerCardSettingDetailContent> contentList=electronicMembershipCardService.getCardSettingDetailContents(contentQuery);
        for (CustomerCardSettingDetailContent content : contentList) {
            if (amt.compareTo(content.getRechargeAmtLowerLimit()) >=0 && amt.compareTo(content.getRechargeAmtUpperLimit())<0) {
                couponInfoSettingDetail.setCcsdId(cardDetail.getCardSettingDetailId().longValue());
                couponInfoSettingDetail.setCouponId(content.getCouponIssueId());
                return couponInfoSettingDetail;

            }
        }
    }
    return null;
}*/

    //计算赠送金额
    public CalPresentAmt calPresentAmt(List<CustomerCardSetting> cardRechargeSettingList,String cardOilsType, BigDecimal amt,RechargeBalance rechargeBalance,String payType,boolean checkVipDay) {
        CalPresentAmt calPresentAmt=new CalPresentAmt();
        BigDecimal presentAmt = BigDecimal.ZERO;
        if (cardRechargeSettingList != null && cardRechargeSettingList.size() == 1) {
            CustomerCardSetting cardSetting = cardRechargeSettingList.get(0);
            CustomerCardSettingDetail form = new CustomerCardSettingDetail();
            //form.setParentId(cardSetting.getId());
            //form.setActivityType(CustomerCardSettingDetail.ACTIVITYTYPE_BALANCE);
            form.setDelFlag("0");
            form.setCardType(cardOilsType);
            form.setEnterpriseId(rechargeBalance.getEnterpriseId().longValue());
            form.setStationId(rechargeBalance.getStationId().longValue());
            form.setStatus("NORMAL");
            form.setActivityMode(CustomerCardSettingDetail.ACTIVITY_MODE_RECHARGE);
            form.setPayType(payType);
            form.setActivityType(CustomerCardSettingDetail.ACTIVITYTYPE_BALANCE);  //只查找增额的活动，优惠劵类型不判断

            form.setNowDate(new Date());
            form.setWeeklySelection(CustomerCardSettingDetail.dateToWeek(new Date()));
            form.setMonthlySelection(CustomerCardSettingDetail.dateToMonth(new Date()));
            List<CustomerCardSettingDetail> customerCardSettingDetails = electronicMembershipCardService.selectCardSettingDetail(form);


            if (!customerCardSettingDetails.isEmpty()) {
                List<Integer> ids = customerCardSettingDetails.stream().filter(d->customerCardSettingDetailService.checkEffectiveTime(d)).map(CustomerCardSettingDetail::getCardSettingDetailId).collect(Collectors.toList());
                if(ids.size()>0){
                    List<CustomerCardSettingDetailContent> contentList = electronicMembershipCardService.queryCardSettingDetailContentsByCcsdIdsBetweenAmt(ids, amt);
                    for (CustomerCardSettingDetailContent content : contentList) {
                        if(amt.compareTo(content.getRechargeAmtLowerLimit()) >=0 && amt.compareTo(content.getRechargeAmtUpperLimit())<0){
                            int ccsdId = Math.toIntExact(content.getCcsdId());
                            Optional<CustomerCardSettingDetail> first = customerCardSettingDetails.stream().filter(d -> d.getCardSettingDetailId() == ccsdId).findFirst();
                            if (first.isPresent()) {
                                CustomerCardSettingDetail cardDetail = first.get();
                                calPresentAmt.setCcsdId(content.getCcsdId());
                                if (cardDetail.getSettingRuleType().equals("1")) { //按充值金额
                                    presentAmt = content.getPresentAmount(); //当前赠送金额
                                } else if (cardDetail.getSettingRuleType().equals("2")) {      //按充值金额的比例
                                    presentAmt = amt.multiply(content.getPresentAmount().multiply(DecimalConstant.O_01)); //当前赠送金额比例的赠送积分
                                }
                            }
                            break;
                        }
                    }
                }

            }


            //循环优惠规则明细
//            outLoop:
//            for (CustomerCardSettingDetail cardDetail : customerCardSettingDetails) {
//                CustomerCardSettingDetailContent contentQuery=new CustomerCardSettingDetailContent();
//                contentQuery.setCcsdId(cardDetail.getCardSettingDetailId().longValue());
//                List<CustomerCardSettingDetailContent> contentList=electronicMembershipCardService.getCardSettingDetailContents(contentQuery);
//                for (CustomerCardSettingDetailContent content : contentList) {
//                    // 判断金额
//                    if(amt.compareTo(content.getRechargeAmtLowerLimit()) >=0 && amt.compareTo(content.getRechargeAmtUpperLimit())<0){
//                        calPresentAmt.setCcsdId(cardDetail.getCardSettingDetailId().longValue());
//                        if (cardDetail.getSettingRuleType().equals("1")) { //按充值金额
//                            presentAmt = content.getPresentAmount(); //当前赠送金额
//                        } else if (cardDetail.getSettingRuleType().equals("2")) {      //按充值金额的比例
//                            presentAmt = amt.multiply(content.getPresentAmount().multiply(DecimalConstant.O_01)); //当前赠送金额比例的赠送积分
//                        }
//                        break outLoop;
//                    }
//                }
//            }
            logger.info("日常活动"+presentAmt.toString());
            if (checkVipDay) {
                if (cardSetting.getDiscountTimeSetting().equals("1")) {
                    String discountTime = cardSetting.getDiscountTime();
                    String[] dctime;     //会员充值活动时间
                    if (StringUtils.isNotBlank(discountTime)) {
                        if (discountTime.contains(",")) {
                            dctime = discountTime.split(",");
                        } else {
                            dctime = new String[1];
                            dctime[0] = discountTime;
                        }
                    }else{
                        log.error("会员充值活动时间为空,id:{}",cardSetting.getId());
                        calPresentAmt.setPresentAmt(presentAmt);
                        return calPresentAmt;
                    }
                    String currentTime = null;

                    String startTimeStr = cardSetting.getStartTime();
                    String endTimeStr = cardSetting.getEndTime();
                    LocalTime startTime = null;
                    LocalTime endTime = null;


                    if (endTimeStr != null && startTimeStr != null) {
                        startTime = LocalTime.parse(startTimeStr);
                        endTime = LocalTime.parse(endTimeStr);
                    }

                    LocalDateTime now = LocalDateTime.now();
                    LocalTime nowTime = now.toLocalTime();

                    String discountTimeType = cardSetting.getDiscountTimeType();     //获取日期类型
                    switch (discountTimeType) {
                        case "1":   //  1.按周来 数据库存的下标从零开始，星期日是零，星期一是1
                            int week = now.getDayOfWeek().getValue();
                            currentTime = String.valueOf(week == 7 ? 0 : week);
                            break;
                        case "2":   //  2.每月的多少号 数据库存的下标从零开始
                            currentTime = String.valueOf(now.getDayOfMonth()-1); //当前时间
                            break;
                        case "3":   //  3.固定日期
                            currentTime = now.toLocalDate().toString();
                            break;
                    }
                    for (String str : dctime) {
                        if (str.equals(currentTime)) {  //如果当前时间在会员日活动时间内
                            //计算会员日内的总赠送金额
                            if (cardSetting.getPresentScale() != null) {
                                if(timeInScope(nowTime,startTime,endTime)){
                                    presentAmt = presentAmt.add(amt.multiply(new BigDecimal(cardSetting.getPresentScale()).multiply(DecimalConstant.O_01)));
                                }
                            }
                            break;
                        }
                    }
                }
            }
        }
        calPresentAmt.setPresentAmt(presentAmt);
        return calPresentAmt;
    }

    private Boolean timeInScope(LocalTime comparedTime ,LocalTime startTime, LocalTime endTime){
//        LocalTime nowTime = LocalTime.of(5,54,07);
        if(startTime == null || endTime == null){
            return true;  // 有一个为null 直接放行
        }else if(startTime.isBefore(endTime) && startTime.isBefore(comparedTime) && endTime.isAfter(comparedTime) ){
            return true;
            //  大 小
        }else if(startTime.isAfter(endTime) ){
            //小 大
            if(startTime.isBefore(comparedTime)){
                return true;
            }
            //大 小
            if(endTime.isAfter(comparedTime)){
                return true;
            }
        }else if(startTime.equals(comparedTime)){
            return true;
        }else if(endTime.equals(comparedTime)){
            return true;
        }
        return false;
    }

    //公众号充值拉起第三方支付
    @RequestMapping(value = "/rechargeToThirdPayment", method = RequestMethod.POST)
    @ApiOperation(value = "公众号充值拉起第三方支付", httpMethod = "POST", notes = "公众号充值拉起第三方支付")
    public String rechargeToThirdPayment(@RequestBody RechargeBalance rechargeBalance) throws Exception {
        Gson gson = new Gson();
        ResultData resultData = null;
        if(rechargeBalance !=null && StringUtils.isNotBlank(rechargeBalance.getAmt()) && StringUtils.isNotBlank(rechargeBalance.getOpenId())
                && StringUtils.isNotBlank(rechargeBalance.getUserType()) && rechargeBalance.getStationId() !=null && StringUtils.isNotBlank(rechargeBalance.getOrderNo())) {
            //String amt = rechargeBalance.getAmt();
            String openId = rechargeBalance.getOpenId();    //公众号的openId
            Integer stationId = rechargeBalance.getStationId();

            String userType = "1";
            String ordNo = rechargeBalance.getOrderNo();
            CustomerCardUseRecord customerCardUseRecord = new CustomerCardUseRecord();
            customerCardUseRecord.setOrderNo(ordNo);
            CustomerCardUseRecord cardRecordByOrderNo = electronicMembershipCardService.getCardRecordByOrderNo(customerCardUseRecord);





            if(cardRecordByOrderNo !=null ){
                if(cardRecordByOrderNo.getStatus() !=null && cardRecordByOrderNo.getStatus().equals("0")){
                    //获取油站的支付配置项信息
                    PayWay payWay = new PayWay();

                    payWay.setStationId(Integer.valueOf(stationId));
                    payWay.setAppType(userType);        //支付宝还是微信
                    payWay.setUseType("0");             //使用类型
                    //获取该油站的支付类型
                    List<PayWay> payWayList = enterpriseService.selectStaPayWay(payWay);
                    HashMap<String, Object> resultMap = new HashMap<>();
                    if(payWayList !=null && payWayList.size() == 1){
                        payWay = payWayList.get(0);
                        if(payWay.getServiceCharge() != null){
                            cardRecordByOrderNo.setServiceCharge(cardRecordByOrderNo.getAmt().divide(new BigDecimal(1000),4,BigDecimal.ROUND_HALF_UP).multiply(payWay.getServiceCharge()));
                        }
                        cardRecordByOrderNo.setPayWayId(payWay.getPayWayId().longValue());
                        //当前油站的支付方式 是随行付还云闪付
                        String payTypeSta = payWayList.get(0).getPayType();
                        String mno = payWayList.get(0).getMno();    //商户号
                        String cardName ="";
                        switch (cardRecordByOrderNo.getCardOilsType()){
                            case "0":
                                cardName = "通用";
                                break;
                            case "1":
                                cardName = "汽油";
                                break;
                            case "2":
                                cardName = "柴油";
                                break;
                            case "3":
                                cardName = "LNG";
                                break;
                            case "4":
                                cardName = "CNG";
                                break;
                        }
                        String subject = cardName+ "电子卡" + " - " +cardRecordByOrderNo.getStationName();
                        String notifyUrl = "";
                        //公众号
                        String appId  = payWayList.get(0).getEnterprise().getGzhAppId();


                        String userId="";
                        List<AppUserInfo>appUserInfos=appUserInfoService.selectAppUserInfoByMobilePhoneAndStationId(AppUserInfo.builder().mobilePhone(cardRecordByOrderNo.getMobilePhone()).stationId(payWayList.get(0).getEnterpriseId()).build());
                        if(appUserInfos!=null&&appUserInfos.size()>0){
                            if(appUserInfos.get(0).getYunhuaUserId()!=null){
                                userId=appUserInfos.get(0).getYunhuaUserId();
                            }else {
                                userId=appUserInfos.get(0).getMobilePhone();
                            }
                        }

                        switch (payTypeSta){
                            case "1":   //随行付
                                SXFPayParam sxfPayParam = new SXFPayParam();
                                sxfPayParam.setAmt(cardRecordByOrderNo.getAmt().toString());
                                sxfPayParam.setAppId(appId);
                                sxfPayParam.setMno(mno);
                                sxfPayParam.setOrdNo(ordNo);
                                //notifyUrl = "https://"+domainName+"/" +"apipay/getCardRechargeCallback";
                                notifyUrl = "https://"+domainName+"/" + contextPath+"/getCardRechargeCallback";
                                sxfPayParam.setNotifyUrl(notifyUrl);
                                sxfPayParam.setSubject(subject);
                                sxfPayParam.setUserId(openId);
                                sxfPayParam.setUserType(userType);
                                sxfPayParam.setWeChatType("2");

                                String ledgerAccountFlag = "0";

                                sxfPayParam.setLedgerAccountFlag(ledgerAccountFlag);
                                resultMap = SXFPayUtil.tradeJsApiScan(sxfPayParam);
                                resultMap.put("merchantsNumber","111111");
                                break;
                            case "2":   //圈圈（元闪付，扫呗）
                                SBPayParam sbPayParam = new SBPayParam();
                                sbPayParam.setAmt(cardRecordByOrderNo.getAmt().toString());
                                sbPayParam.setAppId(appId);
                                sbPayParam.setUserType(userType);
                                sbPayParam.setAppPayType("2");
                                String secretKey = payWayList.get(0).getSecretKey();
                                sbPayParam.setKey(secretKey);
                                sbPayParam.setOpenId(openId);
                                String terminalNo = payWayList.get(0).getTerminalNo();
                                sbPayParam.setTerminalId(terminalNo);
                                sbPayParam.setOrdNo(ordNo);
                                sbPayParam.setOrderBody(subject);
                                //notifyUrl = "https://"+domainName+"/"+"apipay/getYunPayGzhCallback";
                                notifyUrl = "https://"+domainName+"/"+contextPath+"/getYunPayGzhCallback";
                                sbPayParam.setNotifyUrl(notifyUrl);
                                sbPayParam.setMerchantNo(mno);
                                resultMap = SBPayUtil.saoBeiTradePay(sbPayParam);
                                break;
                            case "3":   //通联支付
                                if(null != payWayList.get(0).getTlFusFlag() && "1".equals(payWayList.get(0).getTlFusFlag())){
                                    long amtLong = new BigDecimal(cardRecordByOrderNo.getAmt().toString()).multiply(new BigDecimal("100")).longValue();
                                    notifyUrl = "https://"+domainName + contextPath + "/getTLFusClassRechargePayCallback";     //回调地址
                                    String tlFusClassPayType = "WECHAT_PUBLIC";
                                    logger.info("payway支付参数信息：" + payWayList.get(0).getPayWayId());
                                    //获取通联支付的班次标识
                                    String shiftsMask ="";
                                    String shiftsTime ="";
                                    Map<String, String> smat = this.getShiftsMaskAndTime(payWayList.get(0).getPayWayId());
                                    if(null != smat && smat.containsKey("shiftsMask") && smat.containsKey("shiftsTime")){
                                        shiftsMask = smat.get("shiftsMask");
                                        shiftsTime = smat.get("shiftsTime");
                                    }else {
                                        logger.info("未设置班次");
                                    }
                                    logger.info("班次标识：" + shiftsMask + "; 班次时间：" + shiftsTime);
                                    resultMap = TLFusClassPayUtil.tLFusClassPayApply(
                                            TLFusClassPayParam.builder()
                                                    .account(openId)                        //oWL5P5PPF5gFmoDid19Ij_nN5h70  openId oRwjv4iHjSUgxNxOJOQ_60Ln7cno
                                                    .amount(amtLong)
                                                    .backUrl(notifyUrl)
                                                    .bizOrderNo(ordNo)
                                                    .sysId(payWayList.get(0).getTlSysId())
                                                    .tlAppId(payWayList.get(0).getTlAppId())
                                                    .tlAppKey(payWayList.get(0).getTlAppKey())
                                                    .tlOilStationNo(payWayList.get(0).getTlOilStationNo())                 //通联支付所需要的油站编码
                                                    .consumeType("C0001")                                                  //消费类型
                                                    .shiftsMask(shiftsMask)                                                //班次标识
                                                    .shiftsTime(shiftsTime)     //班次时间
                                                    .remark(subject)
                                                    .subAppId(appId)                            //wxb46701bd193ee573 appId wxe1135cd390b38a54
                                                    .payType(tlFusClassPayType)
                                                    .build());
                                }else {
                                    notifyUrl = "https://"+domainName + contextPath + "/getTLRechargePayCallback";
                                    String tlPayType = "1".equals(userType) ? "W06" : "A02";
                                    //logger.info("通联RSA秘钥："+ payWayList.get(0).getAllinpayRSAKey());
                                    resultMap = TLPayUtil.tLTradePay(
                                            TLPayParam.builder()
                                                    .body("body")
                                                    .notifyUrl(notifyUrl)
                                                    .remark("subject")
                                                    .reqSn(ordNo)
                                                    .payType(tlPayType)
                                                    .acct(openId)           //微信用户openId
                                                    .subAppId(appId)        //微信appId
                                                    .sybAppId(payWayList.get(0).getAllinpayAppId())           //通联系统分配的appId
                                                    .SIGN_TYPE("RSA")       //通联验签加密方式  RSA； SM2； MD5；
                                                    .SYB_RSACUSPRIKEY(payWayList.get(0).getAllinpayRSAKey())   //秘钥 RSA； SM2； MD5；
                                                    .cusId(mno)             //商户号
                                                    .trxAmt(new BigDecimal(customerCardUseRecord.getAmt().toString()).multiply(new BigDecimal("100")).longValue())  //单位分
                                                    .build());
                                }
                                break;
                            case "4" :
                                notifyUrl = "https://" + domainName + contextPath + "/JKCardNotice";
                                long amtLong1 = new BigDecimal(cardRecordByOrderNo.getAmt().toString()).multiply(new BigDecimal("100")).longValue();
                                resultMap = JKPayUtil.JKPay(JKPayParam.builder()
                                        .merchantNo(payWayList.get(0).getMno())
                                        .orderNo(ordNo)
                                        .notifyUrl(notifyUrl)
                                        .amt(amtLong1+"")
                                        .appId(appId)
                                        .openId(openId)
                                        .private_pfxPath(private_pfxPath)
                                        .public_certPath(public_certPath)
                                        .payChannelCode("3")
                                        .build());
                                break;
                            case "5":   //云华支付
                                notifyUrl = "https://" + domainName + contextPath + "/yunHuaCardNotice";

                                log.info("充值单号为"+customerCardUseRecord.getAmt()+"");
//                                resultMap = yunHuaPayUtils.yunHuaPay(YunHuaParam.builder()
//                                        .clientOrgCode(payWayList.get(0).getMno())
//                                        .lockFlag("lock")
//                                        .noticeUrl(notifyUrl)
//                                        .partnerCode(payWayList.get(0).getTerminalNo())
//                                        .payChannelId("wx_jsapi")
//                                        .posOrderNo(ordNo)
//                                        .reqTime(nowdate)
//                                        .txnAmt(cardRecordByOrderNo.getAmt())
//                                        .vsOrderNo(ordNo)
//                                        .openId(openId)
//                                        .carRefueling(nowdate)
//                                        .build());
                                String txnDesc = "电子卡充值";
                                resultMap=yunHuaPayUtils.yunHuaPayV2(YunHuaParam.builder()
                                        .partnerCode(payWayList.get(0).getMno())
                                        .posOrderNo(ordNo)
                                        .noticeUrl(notifyUrl)
                                        .txnDesc(txnDesc)
                                        .txnAmt(cardRecordByOrderNo.getAmt())
                                        .userId(userId)
                                        .build(),payWayList.get(0).getSecretKey(),yunHuaPrePayUrl);
                                resultMap.put("merchantsNumber","111111");
                                break;
                        }
                        resultMap.put("thirdPayment", payTypeSta);
//                        String merchantsNumber ="";
//                        if(resultMap.containsKey("merchantsNumber")){
//                            merchantsNumber = resultMap.get("merchantsNumber").toString();
//                        }
//                        electronicMembershipCardService.updateCardRecordStatusByOrderNo(CustomerCardUseRecord.builder()
//                                .merchantsNumber(merchantsNumber)
//                                .orderNo(ordNo).build());
                        resultData = ResultData.success(resultMap);
                        electronicMembershipCardService.updateCardUseRecordRecharge(cardRecordByOrderNo);
                    }else {
                        resultData = ResultData.error(CodeMsg.NOT_PAYWAY);
                    }
                }else {
                    resultData = ResultData.error(CodeMsg.ALREADY_PAY);
                }
            }else {
                resultData=ResultData.error(CodeMsg.YEWU_FAIL,"未查询到订单");
            }
        }
        logger.info(gson.toJson(resultData));
        return gson.toJson(resultData);
    }

    /*
     * 小程序公众号消费 通联智U+，需要实时到账，分账时 获取班次时间与班次标识
     * @param payWayId
     * @return
     * @throws ParseException
     */
    public Map<String, String> getShiftsMaskAndTime(Integer payWayId) throws ParseException {
        Map<String, String> resultMap = new HashMap<>();
        if(null != payWayId){
            String shiftsMask ="";
            String shiftsTime ="";
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            List<ShiftClass> shiftClassList = enterpriseService.selectShiftClassList(ShiftClass.builder().payWayId(payWayId).build());
            if(null != shiftClassList && shiftClassList.size()>0){
                for (ShiftClass sc : shiftClassList){
                    //如果开始时间小于结束时间，做处理
                    if(sc.getShiftStartTime().compareTo(sc.getShiftEndTime()) <=0){
                        if(sdf.format(new Date()).compareTo(sc.getShiftStartTime().toString()) >=0 && sdf.format(new Date()).compareTo(sc.getShiftEndTime().toString()) <0){
                            shiftsMask = sc.getShiftMask();
                            shiftsTime = DateFormatUtils.format(new Date(), "yyyyMMdd");
                            break;
                        }
                    }else {
                        //否则开始时间大于结束时间
                        if(sdf.format(new Date()).compareTo(sc.getShiftStartTime().toString()) >=0 && sdf.format(new Date()).compareTo("23:59:59") <=0){
                            shiftsMask = sc.getShiftMask();
                            shiftsTime = DateFormatUtils.format(new Date(), "yyyyMMdd");
                            break;
                        }
                        if(sdf.format(new Date()).compareTo("00:00:00") >=0 && sdf.format(new Date()).compareTo(sc.getShiftEndTime().toString()) <0){
                            shiftsMask = sc.getShiftMask();
                            shiftsTime = LocalDate.now().plusDays(-1).toString().replace("-", "");
                            break;
                        }
                    }
                }
            }
            logger.info("shiftsMask：" + shiftsMask + "; shiftsTime:" + shiftsTime);
            resultMap.put("shiftsMask", shiftsMask);
            resultMap.put("shiftsTime", shiftsTime);
        }
        return resultMap;
    }

    @RequestMapping(value = "/getTLFusClassRechargePayCallback", consumes = "application/x-www-form-urlencoded", method = RequestMethod.POST)
    @Transactional
    public void getTLFusClassRechargePayCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {
        JSONObject resultJson = new JSONObject();
        logger.info("========================================公众号电子卡通联智U+，需要实时到账，分账时预支付接口 回调开始 ========================================");
        System.out.println("公众号电子卡通联支付接收到通知");
        request.setCharacterEncoding("UTF-8");//通知传输的编码为GBK
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        TreeMap<String, String> params = getParams(request);//动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容
        logger.info("公众号电子卡通联智U+，需要实时到账，分账返回TreeMap参数：" + params.toString());
        try {
            Map<String, String> bizContent = JSONObject.parseObject(params.get("bizContent"), Map.class);
            //logger.info("bizContent内容信息：" + bizContent);
            String ordNo = bizContent.get("bizOrderNo");    //商户订单号
            String orderNo = bizContent.get("orderNo");     //通联订单号
            String amt = bizContent.get("amount").toString();
            String finishTime = bizContent.get("finishTime");
            CustomerCardUseRecord customerCardUseRecordInfo = electronicMembershipCardService.getCardRecordByOrderNo(CustomerCardUseRecord.builder().orderNo(ordNo).build());
            String ccurPayType = "WECHAT_PUBLIC".equals(bizContent.get("payType")) ? "wx" : "wx";
            //获取油站的支付配置项信息
            PayWay payWay = new PayWay();
            payWay.setStationId(customerCardUseRecordInfo.getStationId());
            payWay.setAppType("1");
            payWay.setUseType("0");             //使用类型
            //获取该油站的支付类型
            List<PayWay> payWayList = enterpriseService.selectStaPayWay(payWay);
            params.put("key", payWayList.get(0).getTlAppKey());
            boolean isSign = SignUtils.verify(params);
            logger.info("公众号电子卡通联智U+，实时到账，分账回调验签结果：" + isSign);
            if(isSign){
                resultJson.put("code", "SUCCESS");
                resultJson.put("msg", "SUCCESS");
                resultJson.put("bizCode", "0000");
                resultJson.put("bizMsg", "SUCCESS");
                TreeMap<String, String> map = new TreeMap<String, String>();
                map.put("code", "SUCCESS");
                map.put("msg", "SUCCESS");
                map.put("bizCode", "0000");
                map.put("bizMsg", "SUCCESS");
                map.put("key", payWayList.get(0).getTlAppKey());
                String sign = SignUtils.sign(map);
                resultJson.put("sign", sign);
                logger.info("公众号电子卡充值通联智U+，实时到账，分账回调验签成功");
                if(null != customerCardUseRecordInfo  && "0".equals(customerCardUseRecordInfo.getStatus())){
                    logger.info("公众号电子卡充值通联智U+，实时到账，分账充值单号：" + ordNo);
                    //查询客户该油品电子卡信息
                    //是否有赠送金额
                    BigDecimal presentAmt =BigDecimal.ZERO;
                    if(customerCardUseRecordInfo.getPresentAmt() !=null){
                        presentAmt = customerCardUseRecordInfo.getPresentAmt();  //客户充值赠送金额
                        logger.info("公众号电子卡充值通联智U+，实时到账，分账 客户充值赠送金额：" +presentAmt.toString());
                    }

                    Station station = enterpriseService.selectStationById(customerCardUseRecordInfo.getStationId());
                    Enterprise enterprise = station.getEnterprise();
                    boolean cardUsingForAll = StringUtils.equals("1",enterprise.getCardUseRangeFlag());

                    //获取客户充值的得电子卡信息
                    logger.info("用户手机号：" + customerCardUseRecordInfo.getMobilePhone() + "; 油企ID：" + station.getEnterpriseId() + "; 卡类型：" + customerCardUseRecordInfo.getCardOilsType());
                    AppUserInfo userinfo = new AppUserInfo();
                    userinfo.setMobilePhone(customerCardUseRecordInfo.getMobilePhone());
                    CustomerElectronicCard electronicCardInfo = electronicMembershipCardService.getAndCreateCustomerElectronicCard(userinfo,customerCardUseRecordInfo.getCardOilsType(), station);
                    if(electronicCardInfo !=null){
                        if(presentAmt.compareTo(BigDecimal.ZERO)>0){
                            //充值赠额记录
                            customerCardSettingDetailService.createRecord(presentAmt,PresentAmountRecord.businessName_customerCardUseRecord,customerCardUseRecordInfo.getMobilePhone(),ordNo,
                                    PresentAmountRecord.purpose_add,electronicCardInfo.getId().longValue(),customerCardUseRecordInfo.getCcsdId());
                        }

                        logger.info(" 公众号电子卡充值通联智U+，实时到账，分账 客户当前原有金额：" + electronicCardInfo.getAmt().toString());
                        BigDecimal afterAmt = electronicCardInfo.getAmt().add(new BigDecimal(amt).multiply(DecimalConstant.O_01));
                        electronicCardInfo.setAmt(afterAmt);
                        BigDecimal afterPresentAmt = electronicCardInfo.getPresentAmt().add(presentAmt);
                        electronicCardInfo.setPresentAmt(afterPresentAmt);
                        //BigDecimal newBalance = electronicCardInfo.getAmt().add(new BigDecimal(amt).divide(new BigDecimal("100"))).add(presentAmt);   //客户新的余额
                        BigDecimal newBalance = electronicCardInfo.getTotalAmt();
                        //电子卡充值方式
                        if(StringUtils.isNotBlank(customerCardUseRecordInfo.getMobilePhone()) && null != customerCardUseRecordInfo.getStationId()){
                            //更新充值记录的状态和余额
                            electronicMembershipCardService.updateCardRecordStatusByOrderNo(CustomerCardUseRecord.builder()
                                    .payType(ccurPayType)
                                    .balance(newBalance)
                                    .transactionId(null)
                                    .payTime(new SimpleDateFormat("yyyyMMddHHmmss").parse(finishTime))
                                    .orderNo(ordNo)
                                    .status("1")
                                    .build());
                            //更新客户余额
                            CustomerElectronicCard.CustomerElectronicCardBuilder builder = CustomerElectronicCard.builder()
                                    .cardOilsType(customerCardUseRecordInfo.getCardOilsType())
                                    .mobilePhone(electronicCardInfo.getMobilePhone())
                                    .recentlyTime(new Date())
                                    .amt(afterAmt)
                                    .presentAmt(afterPresentAmt);

                            if (cardUsingForAll) {
                                builder.stationId(station.getEnterpriseId());
                            }else{
                                builder.stationId2(station.getStationId());
                            }

                            electronicMembershipCardService.updateElectronicCardInfoByPhone(builder.build());
                            //更新参与立减活动的优惠余额
                            reductionActivityBalanceRecordService.createBalanceRecord(ordNo,customerCardUseRecordInfo.getCardOilsType(),new BigDecimal(amt).divide(new BigDecimal("100")),station,null,electronicCardInfo.getMobilePhone(),enterprise,"wx");

                            //充值活动发券
                            couponController.sendCounponByCardUserRecord(ordNo);
                            //充值活动送积分
                            Integral integral = electronicMembershipCardService.rechargeActivityGiveIntegral(ordNo);

                            logger.info("客户当前充值后应有金额：" + newBalance.toString());
                            logger.info("===========公众号电子卡充值通联智U+，实时到账，分账 客户电子会员卡充值成功已到账====");
                            //获取要推送充值成功模板的ID
                            GzhNewsTemplate gzhNewsTemplateInfo = gzhNewsTemplateService.getGzhNewsTemplate(GzhNewsTemplate.builder()
                                    .stationId(station.getEnterpriseId())
                                    .templateType("3")      //3 代表电子会员卡充值成功模板类型
                                    .build());
                            if(gzhNewsTemplateInfo !=null && gzhNewsTemplateInfo.getTemplateId() !=null){
                                logger.info("当前要推送消息所用使用的模板ID："+ gzhNewsTemplateInfo.getTemplateId());
                                enterprise = enterpriseService.selectEnterpriseInfo(station.getEnterpriseId());
                                if(enterprise !=null && StringUtils.isNotBlank(enterprise.getGzhAppId()) && StringUtils.isNotBlank(enterprise.getGzhAppSecret())){
                                    String gzhAppId = enterprise.getGzhAppId();
                                    String gzhAppSecret = enterprise.getGzhAppSecret();
                                    //AppUserInfo appUserInfo = appUserInfoService.getAppUserInfo(AppUserInfo.builder().mobilePhone(customerCardUseRecordInfo.getMobilePhone()).stationId(station.getEnterpriseId()).build());
                                    if(StringUtils.isNotBlank(customerCardUseRecordInfo.getBlogOpenid())){
                                        //List<WxMpTemplateData> wxMpTemplate = new ArrayList<>();
                                        String cardName = "";
                                        switch (customerCardUseRecordInfo.getCardOilsType()){
                                            case "0":
                                                cardName = "通用";
                                                break;
                                            case "1":
                                                cardName = "汽油";
                                                break;
                                            case "2":
                                                cardName = "柴油";
                                                break;
                                            case "3":
                                                cardName = "LNG";
                                                break;
                                            case "4":
                                                cardName = "CNG";
                                                break;
                                        }
//                                        wxMpTemplate.add(new WxMpTemplateData("first","尊敬的"+customerCardUseRecordInfo.getCustomerName()+"，您好：\n" + "您在"+station.getStationName()+"的"+cardName+"电子卡充值成功信息如下"));
//                                        wxMpTemplate.add(new WxMpTemplateData("keyword1", electronicCardInfo.getCustomerNo()));
//                                        wxMpTemplate.add(new WxMpTemplateData("keyword2", new BigDecimal(amt).divide(new BigDecimal("100")).toString()+ " 元"));
//                                        wxMpTemplate.add(new WxMpTemplateData("keyword3", presentAmt.toString()+ " 元"));
//                                        wxMpTemplate.add(new WxMpTemplateData("keyword4", newBalance.toString()+ " 元"));
//                                        wxMpTemplate.add(new WxMpTemplateData("keyword5", new SimpleDateFormat("yyyy年MM月dd日HH时mm分").format(new Date())));
//                                        wxMpTemplate.add(new WxMpTemplateData("remark","感谢您在"+ station.getStationName()+"的本次充值！"));
//                                        logger.info("要推送的消息内容：" +wxMpTemplate.toString());
//                                        wxPushUtil.push(gzhAppId, gzhAppSecret, gzhNewsTemplateInfo.getTemplateId(), customerCardUseRecordInfo.getBlogOpenid(), wxMpTemplate);

                                        String notifyName = station.getStationName() == null ? enterprise.getEnterpriseName():station.getStationName();
                                        WxTemplateMsg wxTemplateMsg = new WxTemplateMsg();
                                        wxTemplateMsg.setTemplate_id(gzhNewsTemplateInfo.getTemplateId());
                                        wxTemplateMsg.setTouser(customerCardUseRecordInfo.getBlogOpenid());
                                        Map<String, WxTemplateData> templateDataMap = new HashMap<>();
                                        templateDataMap.put("first",      WxTemplateData.builder().value("尊敬的"+customerCardUseRecordInfo.getCustomerName()+"您好：" + "您在"+notifyName+"的"+cardName+"电子卡充值成功信息如下").build());
                                        templateDataMap.put("keyword1",   WxTemplateData.builder().value(electronicCardInfo.getCustomerNo()).build());
                                        templateDataMap.put("keyword2",   WxTemplateData.builder().value(new BigDecimal(amt).divide(new BigDecimal("100")).toString() + " 元").build());
                                        templateDataMap.put("keyword3",   WxTemplateData.builder().value(presentAmt.toString()+ " 元").build());
                                        templateDataMap.put("keyword4",   WxTemplateData.builder().value(newBalance.toString()+ " 元").build());
                                        templateDataMap.put("keyword5",   WxTemplateData.builder().value(new SimpleDateFormat("yyyy年MM月dd日HH时mm分").format(new Date())).build());
                                        templateDataMap.put("remark",     WxTemplateData.builder().value("感谢您在"+ notifyName+"的本次充值！").build());
                                        wxTemplateMsg.setData(templateDataMap);
                                        wxPushUtil.sendTemplateMsg(gzhAppId, gzhAppSecret, wxTemplateMsg);

                                        logger.info("===================================公众号电子卡充值通联智U+，实时到账，分账 本次电子卡充值流程结束===========================================");
                                    }
                                }
                            }
                        }else {
                            logger.info("么有手机号和油站ID");
                        }
                    }
                }
            }else {
                logger.info("公众号电子卡充值通联智U+，实时到账，分账回调验签失败");
            }
        }catch (Exception e) {//处理异常
            logger.error("通联充值电子卡失败",e);
        }
        finally{//收到通知,返回success
            response.getOutputStream().write(resultJson.toString().getBytes());
            response.flushBuffer();
        }

    }


    // 金控接受异步异步通知
    @RequestMapping(value = "/JKCardNotice", consumes = "application/json", method = RequestMethod.POST)
    public void JKCardNotice(HttpServletRequest request, HttpServletResponse response) {
        // 接受异步消息
        try {
            String data = JKPayUtil.getParamByStream(request);
            JSONObject obj = JSON.parseObject(data);
            logger.info("金控回调开始参数"+data);
            obj.put("orderInfo", obj.getString("orderInfo").replaceAll(" ", "+"));
            obj.put("signValue", obj.getString("signValue").replaceAll(" ", "+"));
            String signvalue = obj.getString("signValue");
            obj.remove("signValue");
            Map verifyMap = (Map) JSONObject.parse(obj.toString());
            String verifyContent = ParaUtils.createLinkString(ParaUtils.paraFilter(verifyMap));
            boolean checkverify = CfcaCertUtil.verifyValue(verifyContent, signvalue, public_certPath);
            if (checkverify) { //验签成功
                String orderInfo = Base64Util.decodeString(obj.get("orderInfo") + "");
                logger.info(orderInfo);
                JSONObject orderInfoMessage = JSON.parseObject(orderInfo);
                if (!"02".equals(orderInfoMessage.get("orderStatus")+"")) {
                    logger.info("金控返回订单处理失败"+orderInfoMessage);
                    response.getWriter().print("000000");
                    throw  new  Exception("支付失败消息为+"+orderInfoMessage);
                }
                //引用相应的参数
                String ordNo = orderInfoMessage.get("mfhcdOrderNo") + "";    //商户订单号

                String amt = orderInfoMessage.get("tranAmt").toString();
                String finishTime = orderInfoMessage.get("transFinishTime") + "";
                //通过商户订单号查找对应的充值记录
                CustomerCardUseRecord customerCardUseRecordInfo = electronicMembershipCardService.getCardRecordByMerchantsNumber(CustomerCardUseRecord.builder().merchantsNumber(ordNo).build());
                if (null != customerCardUseRecordInfo && "0".equals(customerCardUseRecordInfo.getStatus())) {
                    logger.info("公众号电子卡充值金控，分账充值单号：" + ordNo);
                    //查询客户该油品电子卡信息
                    //是否有赠送金额
                    BigDecimal presentAmt = BigDecimal.ZERO;
                    if (customerCardUseRecordInfo.getPresentAmt() != null) {
                        presentAmt = customerCardUseRecordInfo.getPresentAmt();  //客户充值赠送金额
                        logger.info("公众号电子卡充值金控，客户充值赠送金额：" + presentAmt.toString());
                    }

                    Station station = enterpriseService.selectStationById(customerCardUseRecordInfo.getStationId());
                    Enterprise enterprise = station.getEnterprise();
                    boolean cardUsingForAll = StringUtils.equals("1",enterprise.getCardUseRangeFlag());


                    //获取客户充值的得电子卡信息
                    logger.info("用户手机号：" + customerCardUseRecordInfo.getMobilePhone() + "; 油企ID：" + station.getEnterpriseId() + "; 卡类型：" + customerCardUseRecordInfo.getCardOilsType());

                    AppUserInfo userinfo = new AppUserInfo();
                    userinfo.setMobilePhone(customerCardUseRecordInfo.getMobilePhone());
                    CustomerElectronicCard electronicCardInfo = electronicMembershipCardService.getAndCreateCustomerElectronicCard(userinfo,customerCardUseRecordInfo.getCardOilsType(), station);

                    if (electronicCardInfo != null) {
                        if(presentAmt.compareTo(BigDecimal.ZERO)>0){
                            //充值赠额记录
                            customerCardSettingDetailService.createRecord(presentAmt,PresentAmountRecord.businessName_customerCardUseRecord,customerCardUseRecordInfo.getMobilePhone(),ordNo,
                                    PresentAmountRecord.purpose_add,electronicCardInfo.getId().longValue(),customerCardUseRecordInfo.getCcsdId());
                        }

                        logger.info(" 公众号电子卡充值金控，实时到账，分账 客户当前原有金额：" + electronicCardInfo.getAmt().toString());
                        BigDecimal afterAmt = electronicCardInfo.getAmt().add(new BigDecimal(amt).multiply(DecimalConstant.O_01));
                        electronicCardInfo.setAmt(afterAmt);
                        BigDecimal afterPresentAmt = electronicCardInfo.getPresentAmt().add(presentAmt);
                        electronicCardInfo.setPresentAmt(afterPresentAmt);
                        //BigDecimal newBalance = electronicCardInfo.getAmt().add(new BigDecimal(amt).divide(new BigDecimal("100"))).add(presentAmt);   //客户新的余额
                        BigDecimal newBalance = electronicCardInfo.getTotalAmt();
                        //电子卡充值方式
                        if (StringUtils.isNotBlank(customerCardUseRecordInfo.getMobilePhone()) && null != customerCardUseRecordInfo.getStationId()) {
                            //更新充值记录的状态和余额
                            electronicMembershipCardService.updateCardRecordStatusByOrderNo(CustomerCardUseRecord.builder()
                                    .payType("wx")
                                    .balance(newBalance)
                                    .transactionId(null)
                                    .payTime(new SimpleDateFormat("yyyyMMddHHmmss").parse(finishTime))
                                    .orderNo(customerCardUseRecordInfo.getOrderNo())
                                    .status("1")
                                    .build());
                            //更新客户余额
                            CustomerElectronicCard.CustomerElectronicCardBuilder builder = CustomerElectronicCard.builder()
                                    .cardOilsType(customerCardUseRecordInfo.getCardOilsType())
                                    .mobilePhone(electronicCardInfo.getMobilePhone())
                                    .recentlyTime(new Date())
                                    .amt(afterAmt)
                                    .presentAmt(afterPresentAmt);
                            if (cardUsingForAll) {
                                builder.stationId(station.getEnterpriseId());
                            }else{
                                builder.stationId2(station.getStationId());
                            }
                            electronicMembershipCardService.updateElectronicCardInfoByPhone(builder.build());

                            //更新参与立减活动的优惠余额
                            reductionActivityBalanceRecordService.createBalanceRecord(ordNo,customerCardUseRecordInfo.getCardOilsType(),new BigDecimal(amt).divide(new BigDecimal("100")),station,null,electronicCardInfo.getMobilePhone(),enterprise,"wx");

                            //充值活动发券
                            couponController.sendCounponByCardUserRecord(ordNo);
                            //充值活动送积分
                            Integral integral = electronicMembershipCardService.rechargeActivityGiveIntegral(ordNo);
                            logger.info("客户当前充值后应有金额：" + newBalance.toString());
                            logger.info("===========公众号电子卡充值金控， 客户电子会员卡充值成功已到账====");
                            //获取要推送充值成功模板的ID
                            GzhNewsTemplate gzhNewsTemplateInfo = gzhNewsTemplateService.getGzhNewsTemplate(GzhNewsTemplate.builder()
                                    .stationId(station.getEnterpriseId())
                                    .templateType("3")      //3 代表电子会员卡充值成功模板类型
                                    .build());
                            if (gzhNewsTemplateInfo != null && gzhNewsTemplateInfo.getTemplateId() != null) {
                                logger.info("当前要推送消息所用使用的模板ID：" + gzhNewsTemplateInfo.getTemplateId());
                                enterprise = enterpriseService.selectEnterpriseInfo(station.getEnterpriseId());
                                if (enterprise != null && StringUtils.isNotBlank(enterprise.getGzhAppId()) && StringUtils.isNotBlank(enterprise.getGzhAppSecret())) {
                                    String gzhAppId = enterprise.getGzhAppId();
                                    String gzhAppSecret = enterprise.getGzhAppSecret();
                                    //AppUserInfo appUserInfo = appUserInfoService.getAppUserInfo(AppUserInfo.builder().mobilePhone(customerCardUseRecordInfo.getMobilePhone()).stationId(station.getEnterpriseId()).build());
                                    if (StringUtils.isNotBlank(customerCardUseRecordInfo.getBlogOpenid())) {
                                        //List<WxMpTemplateData> wxMpTemplate = new ArrayList<>();
                                        String cardName = "";
                                        switch (customerCardUseRecordInfo.getCardOilsType()) {
                                            case "0":
                                                cardName = "通用";
                                                break;
                                            case "1":
                                                cardName = "汽油";
                                                break;
                                            case "2":
                                                cardName = "柴油";
                                                break;
                                            case "3":
                                                cardName = "LNG";
                                                break;
                                            case "4":
                                                cardName = "CNG";
                                                break;
                                        }
//                                        wxMpTemplate.add(new WxMpTemplateData("first","尊敬的"+customerCardUseRecordInfo.getCustomerName()+"，您好：\n" + "您在"+station.getStationName()+"的"+cardName+"电子卡充值成功信息如下"));
//                                        wxMpTemplate.add(new WxMpTemplateData("keyword1", electronicCardInfo.getCustomerNo()));
//                                        wxMpTemplate.add(new WxMpTemplateData("keyword2", new BigDecimal(amt).divide(new BigDecimal("100")).toString()+ " 元"));
//                                        wxMpTemplate.add(new WxMpTemplateData("keyword3", presentAmt.toString()+ " 元"));
//                                        wxMpTemplate.add(new WxMpTemplateData("keyword4", newBalance.toString()+ " 元"));
//                                        wxMpTemplate.add(new WxMpTemplateData("keyword5", new SimpleDateFormat("yyyy年MM月dd日HH时mm分").format(new Date())));
//                                        wxMpTemplate.add(new WxMpTemplateData("remark","感谢您在"+ station.getStationName()+"的本次充值！"));
//                                        logger.info("要推送的消息内容：" +wxMpTemplate.toString());
//                                        wxPushUtil.push(gzhAppId, gzhAppSecret, gzhNewsTemplateInfo.getTemplateId(), customerCardUseRecordInfo.getBlogOpenid(), wxMpTemplate);

                                        String notifyName = station.getStationName() == null ? enterprise.getEnterpriseName():station.getStationName();
                                        WxTemplateMsg wxTemplateMsg = new WxTemplateMsg();
                                        wxTemplateMsg.setTemplate_id(gzhNewsTemplateInfo.getTemplateId());
                                        wxTemplateMsg.setTouser(customerCardUseRecordInfo.getBlogOpenid());
                                        Map<String, WxTemplateData> templateDataMap = new HashMap<>();
                                        templateDataMap.put("first", WxTemplateData.builder().value("尊敬的" + customerCardUseRecordInfo.getCustomerName() + "您好：" + "您在" + notifyName + "的" + cardName + "电子卡充值成功信息如下").build());
                                        templateDataMap.put("keyword1", WxTemplateData.builder().value(electronicCardInfo.getCustomerNo()).build());
                                        templateDataMap.put("keyword2", WxTemplateData.builder().value(new BigDecimal(amt).divide(new BigDecimal("100")).toString() + " 元").build());
                                        templateDataMap.put("keyword3",   WxTemplateData.builder().value(presentAmt.toString()+ " 元").build());
                                        templateDataMap.put("keyword4",   WxTemplateData.builder().value(newBalance.toString()+ " 元").build());
                                        templateDataMap.put("keyword5", WxTemplateData.builder().value(new SimpleDateFormat("yyyy年MM月dd日HH时mm分").format(new Date())).build());
                                        templateDataMap.put("remark", WxTemplateData.builder().value("感谢您在" + notifyName + "的本次充值！").build());
                                        wxTemplateMsg.setData(templateDataMap);
                                        wxPushUtil.sendTemplateMsg(gzhAppId, gzhAppSecret, wxTemplateMsg);

                                        logger.info("===================================公众号电子卡充值金控，实时到账，分账 本次电子卡充值流程结束===========================================");
                                    }
                                }
                            }
                        } else {
                            logger.info("么有手机号和油站ID");
                        }
                    }
                }


                response.getWriter().print("000000");
            }


        } catch (Exception e) {
            logger.info("金控回调错误日志+" + e.getMessage());
            e.printStackTrace();
        }

    }



    // 金控接受异步异步通知
    @RequestMapping(value = "/yunHuaCardNotice", consumes = "application/json", method = RequestMethod.POST)
    @Transactional
    public void yunHuaCardNotice(HttpServletRequest request, HttpServletResponse response) {
        // 接受异步消息
        try {
            // 获取当前请求的域名
            //String  requestUrl=request.getRequestURI();
            String reqPayType = request.getParameter("payType");
            String pId = request.getParameter("pId");
            int preId = 0;
            if (StringUtils.isNumeric(pId)) {
                preId = Integer.parseInt(pId);
            }
            String data = JKPayUtil.getParamByStream(request);
            logger.info("云华开始充值回调" + data);
            JSONObject obj = JSON.parseObject(data);
            logger.info("云华开始充值回调" + obj);
            //做域名校验  判断
//            if("".equals(requestUrl)){
//                response.getWriter().print("000000");
//                logger.info("云华回调充值接口失败，请求地址错误");
//                return;
//            }

            String   status=obj.getString("status");
            if ("3".equals(status)) { //验签成功
//                String  orderNo=obj.getString("posOrderNo");//商户订单号
//                BigDecimal amt=obj.getBigDecimal("txnAmt");
//                String  payTime=obj.getString("payTime");


                BigDecimal amt=obj.getBigDecimal("txnAmt");
                String  orderNo=obj.getString("clientSerialNo");
                String  payTime=obj.getString("payTime");
                String  transPayNo=obj.getString("transPayNo");
                String  translnfoNo=obj.getString("transInfoNo");
                String  payOrderNo=obj.getString("payOrderNo");
                String merchantDisAmt = obj.getString("merchantDisAmt");
                String sponsorDisAmt = obj.getString("sponsorDisAmt");
                String marketingDisAmt = obj.getString("marketingDisAmt");
                String platformDisAmt = obj.getString("platformDisAmt");
                String payAmt = obj.getString("payAmt");
//                String amt = orderInfoMessage.get("tranAmt").toString();
//                String finishTime = orderInfoMessage.get("transFinishTime") + "";
                //通过商户订单号查找对应的充值记录
                CustomerCardUseRecord customerCardUseRecordInfo = electronicMembershipCardService.getCardRecordByOrderNo(CustomerCardUseRecord.builder().orderNo(orderNo).build());
                Station station = enterpriseService.selectStationById(customerCardUseRecordInfo.getStationId());
                Enterprise enterprise = station.getEnterprise();
                boolean cardUsingForAll = StringUtils.equals("1",enterprise.getCardUseRangeFlag());
                if (null != customerCardUseRecordInfo && "0".equals(customerCardUseRecordInfo.getStatus())) {
                    logger.info("公众号电子卡充值云华，分账充值单号：" + orderNo);
                    //查询客户该油品电子卡信息
                    //是否有赠送金额
                    BigDecimal presentAmt = BigDecimal.ZERO;
                    if (customerCardUseRecordInfo.getPresentAmt() != null) {
                        presentAmt = customerCardUseRecordInfo.getPresentAmt();  //客户充值赠送金额
                        logger.info("公众号电子卡充值云华，客户充值赠送金额：" + presentAmt.toString());
                    }


                    //获取客户充值的得电子卡信息
                    logger.info("用户手机号：" + customerCardUseRecordInfo.getMobilePhone() + "; 油企ID：" + station.getEnterpriseId() + "; 卡类型：" + customerCardUseRecordInfo.getCardOilsType());
                    AppUserInfo userinfo = new AppUserInfo();
                    userinfo.setMobilePhone(customerCardUseRecordInfo.getMobilePhone());
                    CustomerElectronicCard electronicCardInfo = electronicMembershipCardService.getAndCreateCustomerElectronicCard(userinfo,customerCardUseRecordInfo.getCardOilsType(), station);

                    if (electronicCardInfo != null) {
                        if(presentAmt.compareTo(BigDecimal.ZERO)>0){
                            //充值赠额记录
                            customerCardSettingDetailService.createRecord(presentAmt,PresentAmountRecord.businessName_customerCardUseRecord,customerCardUseRecordInfo.getMobilePhone(),orderNo,
                                    PresentAmountRecord.purpose_add,electronicCardInfo.getId().longValue(),customerCardUseRecordInfo.getCcsdId());
                        }

                        BigDecimal manualPresentAmt = BigDecimal.ZERO;
                        if (preId>0) {
                            // pos机手动输入赠送金额功能
                            CustomerCardUseRecord preRecord = customerCardUseRecordMapper.getById((long) preId);
                            if (preRecord != null) {
                                manualPresentAmt = preRecord.getPresentAmt();
                            }else{
                                preId = 0;
                            }
                        }

                        logger.info(" 公众号电子卡充值金控，实时到账，分账 客户当前原有金额：" + electronicCardInfo.getAmt().toString());
                        BigDecimal afterAmt = electronicCardInfo.getAmt().add(amt);
                        electronicCardInfo.setAmt(afterAmt);
                        BigDecimal afterPresentAmt = electronicCardInfo.getPresentAmt().add(presentAmt);
                        electronicCardInfo.setPresentAmt(afterPresentAmt);
                        //BigDecimal newBalance = electronicCardInfo.getAmt().add(amt).add(presentAmt);   //客户新的余额
                        BigDecimal newBalance = electronicCardInfo.getTotalAmt();

                        BigDecimal afterManPresAmt = electronicCardInfo.getPresentAmt().add(manualPresentAmt);
                        electronicCardInfo.setPresentAmt(afterManPresAmt);
                        BigDecimal afterPresentBalance = electronicCardInfo.getTotalAmt();

                        BigDecimal finalPresentAmt = MathUtil.add(presentAmt, manualPresentAmt);

                        //电子卡充值方式
                        if (StringUtils.isNotBlank(customerCardUseRecordInfo.getMobilePhone()) && null != customerCardUseRecordInfo.getStationId()) {
                            //更新充值记录的状态和余额
                            if (StringUtils.isBlank(reqPayType)) {
                                reqPayType = "wx";
                            }
                            electronicMembershipCardService.updateCardRecordStatusByOrderNo(CustomerCardUseRecord.builder()
                                    .payType(reqPayType)
                                    .balance(newBalance)
                                    .transactionId(null)
                                    .payTime(new Date())
                                    .orderNo(customerCardUseRecordInfo.getOrderNo())
                                    .merchantsNumber(translnfoNo)
                                    .transactionId(transPayNo)
                                    .status("1")
                                    .build());
                            if (preId > 0) {
                                // pos机手动输入赠送金额功能
                                electronicMembershipCardMapper.updateCardUseRecordRecharge(CustomerCardUseRecord.builder()
                                        .balance(afterPresentBalance)
                                        .status("1")
                                        .id(preId)
                                        .build());
                            }
//                            logger.info("云华充值回调暂停开始，手机号："+electronicCardInfo.getMobilePhone());
//                            Thread.sleep(2000);
//                            logger.info("云华充值回调暂停结束，手机号："+electronicCardInfo.getMobilePhone());
                            //更新客户余额
                            CustomerElectronicCard.CustomerElectronicCardBuilder builder = CustomerElectronicCard.builder()
                                    .cardOilsType(customerCardUseRecordInfo.getCardOilsType())
                                    .mobilePhone(electronicCardInfo.getMobilePhone())
                                    .recentlyTime(new Date())
                                    .amt(afterAmt)
                                    .presentAmt(afterManPresAmt);

                            if (cardUsingForAll) {
                                builder.stationId(station.getEnterpriseId());
                            }else{
                                builder.stationId2(station.getStationId());
                            }
                            electronicMembershipCardService.updateElectronicCardInfoByPhone(builder.build());
                            //更新参与立减活动的优惠余额
                            reductionActivityBalanceRecordService.createBalanceRecord(orderNo,customerCardUseRecordInfo.getCardOilsType(),amt,station,null,electronicCardInfo.getMobilePhone(),enterprise,"wx");

                            //充值活动发券
                            couponController.sendCounponByCardUserRecord(orderNo);

                            //充值活动送积分
                            Integral integral = electronicMembershipCardService.rechargeActivityGiveIntegral(orderNo);

                            logger.info("客户当前充值后应有金额：" + newBalance.toString());
                            logger.info("===========公众号电子卡充值金控， 客户电子会员卡充值成功已到账====");
                            //获取要推送充值成功模板的ID
//                            GzhNewsTemplate gzhNewsTemplateInfo = gzhNewsTemplateService.getGzhNewsTemplate(GzhNewsTemplate.builder()
//                                    .stationId(station.getEnterpriseId())
//                                    .templateType("3")      //3 代表电子会员卡充值成功模板类型
//                                    .build());

                            //微信模板消息推送充值成功模板
                            if ("wx_jsapi".equals(obj.getString("channelNo"))) {
                                Map<String, String> templateParams = new HashMap<>();
                                templateParams.put("openid", customerCardUseRecordInfo.getBlogOpenid());
                                templateParams.put("customerNo", electronicCardInfo.getCustomerNo());
                                templateParams.put("amt", amt + "元");
                                templateParams.put("presentAmt", finalPresentAmt + "元");
                                templateParams.put("balance", afterPresentBalance + "元");
                                logger.info("电子卡充值-微信模板参数：{}", templateParams);
                                wxPushUtil.sendTemplateMsg(station.getEnterpriseId(), templateParams, WxTemplateEnum.RECHARGE_SUCCESS);
                                if (integral.getPresentIntegral()>0) {
                                    Map<String, String> integralParams = new HashMap<>();
                                    integralParams.put("openid", customerCardUseRecordInfo.getBlogOpenid());
                                    integralParams.put("stationName", station.getStationName());
                                    integralParams.put("createTime", LocalDateTimeUtil.parse(LocalDateTime.now()));
                                    integralParams.put("integral", String.valueOf(MathUtil.add(null,integral.getPresentIntegral())));
                                    integralParams.put("totalIntegral", String.valueOf(MathUtil.add(null,integral.getTotalIntegral())));
                                    wxPushUtil.sendTemplateMsg(station.getEnterpriseId(),integralParams,WxTemplateEnum.INTEGRAL_CHANGE);
                                }
                            }



                            //发送消息
//                            gzhNewsTemplateService.sendEletricMessage(obj,station,customerCardUseRecordInfo);
                            //打印小票
                            customerCardUseRecordInfo.setIntegral(integral.getPresentIntegral());
                            log.info("customerCardUseRecordInfo======{}",customerCardUseRecordInfo);
                            if (preId > 0) {
                                customerCardUseRecordInfo.setPresentAmt(finalPresentAmt);
                                customerCardUseRecordInfo.setBalance(afterPresentBalance);
                            }
                            gzhNewsTemplateService.elecOrderPush(customerCardUseRecordInfo);

//                            if (gzhNewsTemplateInfo != null && gzhNewsTemplateInfo.getTemplateId() != null) {
//                                logger.info("当前要推送消息所用使用的模板ID：" + gzhNewsTemplateInfo.getTemplateId());
//                                Enterprise enterprise = enterpriseService.selectEnterpriseInfo(station.getEnterpriseId());
//                                if (enterprise != null && StringUtils.isNotBlank(enterprise.getGzhAppId()) && StringUtils.isNotBlank(enterprise.getGzhAppSecret())) {
//                                    String gzhAppId = enterprise.getGzhAppId();
//                                    String gzhAppSecret = enterprise.getGzhAppSecret();
//                                    //AppUserInfo appUserInfo = appUserInfoService.getAppUserInfo(AppUserInfo.builder().mobilePhone(customerCardUseRecordInfo.getMobilePhone()).stationId(station.getEnterpriseId()).build());
//                                    if (StringUtils.isNotBlank(customerCardUseRecordInfo.getBlogOpenid())) {
//                                        //List<WxMpTemplateData> wxMpTemplate = new ArrayList<>();
//                                        String cardName = "";
//                                        switch (customerCardUseRecordInfo.getCardOilsType()) {
//                                            case "0":
//                                                cardName = "通用";
//                                                break;
//                                            case "1":
//                                                cardName = "汽油";
//                                                break;
//                                            case "2":
//                                                cardName = "柴油";
//                                                break;
//                                            case "3":
//                                                cardName = "LNG";
//                                                break;
//                                            case "4":
//                                                cardName = "CNG";
//                                                break;
//                                        }
//
//                                        WxTemplateMsg wxTemplateMsg = new WxTemplateMsg();
//                                        wxTemplateMsg.setTemplate_id(gzhNewsTemplateInfo.getTemplateId());
//                                        wxTemplateMsg.setTouser(customerCardUseRecordInfo.getBlogOpenid());
//                                        Map<String, WxTemplateData> templateDataMap = new HashMap<>();
//                                        templateDataMap.put("first", WxTemplateData.builder().value("尊敬的" + customerCardUseRecordInfo.getCustomerName() + "您好：" + "您在" + station.getStationName() + "的" + cardName + "电子卡充值成功信息如下").build());
//                                        templateDataMap.put("keyword1", WxTemplateData.builder().value(electronicCardInfo.getCustomerNo()).build());
//                                        templateDataMap.put("keyword2", WxTemplateData.builder().value(amt + " 元").build());
//                                        templateDataMap.put("keyword3", WxTemplateData.builder().value(presentAmt.toString() + " 元").build());
//                                        templateDataMap.put("keyword4", WxTemplateData.builder().value(newBalance.toString() + " 元").build());
//                                        templateDataMap.put("keyword5", WxTemplateData.builder().value(new SimpleDateFormat("yyyy年MM月dd日HH时mm分").format(new Date())).build());
//                                        templateDataMap.put("remark", WxTemplateData.builder().value("感谢您在" + station.getStationName() + "的本次充值！").build());
//                                        wxTemplateMsg.setData(templateDataMap);
//                                        wxPushUtil.sendTemplateMsg(gzhAppId, gzhAppSecret, wxTemplateMsg);
//
//                                        logger.info("===================================公众号电子卡充值金控，实时到账，分账 本次电子卡充值流程结束===========================================");
//                                    }
//                                }
//                            }
                        } else {
                            logger.info("么有手机号和油站ID");
                        }
                    }
                }


                response.getWriter().print("{\"code\":\"0000\"}");
            }


        } catch (Exception e) {
            logger.info("金控回调错误日志+" + e.getMessage());
            e.printStackTrace();
        }

    }

    @ApiOperation(value = "校验电子卡重复支付", httpMethod = "GET", notes = "校验电子卡重复支付")
    @RequestMapping(value = "/checkDzkRepeatPay", method = RequestMethod.GET)
    public String checkDzkRepeatPay(@RequestParam String ordNo){
        Gson gson =new Gson();
        ResultData resultData = null;

        PayOrder payOrderInfo = payOrderService.selectOrderInfoByOrdNo(ordNo);
        int i=0;
        if(payOrderInfo!=null){
            i=payOrderService.checkDzkRepeatPay(payOrderInfo);
        }
        if(i>0){
            resultData=ResultData.error(CodeMsg.CHECKDZKREPEATPAY_FAIL);
        }else{
            resultData=ResultData.success(CodeMsg.SUCCESS);
        }

        return gson.toJson(resultData);
    }
    //电子卡支付
    @Transactional
    @RequestMapping(value = "/dzkPaySet", method = RequestMethod.GET)
    @ApiOperation(value = "电子卡支付", httpMethod = "GET", notes = "电子卡支付")
    public  String dzkPaySet(@RequestParam String ordNo, String couponUserId){
        Gson gson =new Gson();
        ResultData resultData = null;
        logger.info("/dzkPaySet-" + ordNo + "--couponUserId:" + couponUserId);
        if(StringUtils.isNotBlank(ordNo)){
            //获取用户订单信息
            PayOrder payOrderInfo = payOrderService.selectOrderInfoByOrdNo(ordNo);
            if(payOrderInfo !=null && payOrderInfo.getStatus().equals("0")){
                logger.info("/dzkPaySet-" + ordNo + "--用户信息：" + payOrderInfo.toString());
                //油站ID
                Integer stationId = payOrderInfo.getStationId();
                //String unionId = payOrderInfo.getUnionId();     //用户unionId
                String oilName =payOrderInfo.getOilName();      //油品名字
                String cardType = payOrderInfo.getCardType();   //该订单对应的油品类型
                String amt = payOrderInfo.getAmt().toString();  //订单支付金额
                //String dzkAmt = payOrderInfo.getDzkAmt().toString();    //电子卡支付金额
                String receivableAmt = payOrderInfo.getReceivableAmt().toString();
                //获取油站信息
                Station stationInfo = enterpriseService.selectStationById(stationId);
                if(null != stationInfo){
                    //获取用户信息
                    AppUserInfo appUserInfo = appUserInfoService.getAppUserInfo(AppUserInfo.builder().mobilePhone(payOrderInfo.getCustomerPhone()).stationId(stationInfo.getEnterpriseId()).build());
                    if(null != appUserInfo && StringUtils.isNotBlank(appUserInfo.getMobilePhone())){
                        if(StringUtils.isNotBlank(couponUserId)){
                            logger.info("电子卡支付时用户使用的优惠券ID：" + couponUserId);
                            //计算使用优惠券后传参优惠券ID
                            payOrderInfo.setDiscountCoupon(couponUserId);
                            //计算优惠券
                            CouponUser couponUser = reductionActivityService.checkCoupon(appUserInfo, payOrderInfo, stationInfo);
                            logger.info("电子卡支付时用户使用的优惠券信息：" + couponUser);
                            if(null != couponUser){
                                PayOrder p = new PayOrder();                            //更新订单参数
                                //使用优惠券时要更新的订单信息
                                amt =couponUser.getNewAmtByCoupon().toString();
                                p.setDiscountCoupon(couponUserId);
                                p.setDiscountCouponAmt(couponUser.getCouponAmtByCNY().doubleValue());
                                p.setAmt(Double.valueOf(amt));
                                p.setOrderNo(ordNo);
                                payOrderService.getUpdatePayOrder(p);
                                logger.info("电子卡支付时用户要付款的金额：" + amt);
                            }
                        }

                        BigDecimal balance = BigDecimal.ZERO;                                                  //电子会员卡余额
                        Integer enterpriseId = stationInfo.getEnterpriseId();
                        //获取用户电子会员卡信息
                        CustomerElectronicCard cardInfo = electronicMembershipCardService.getAndCreateCustomerElectronicCard(appUserInfo,cardType, stationInfo);




                        balance = cardInfo.getTotalAmt();
                        BigDecimal orderAmt = new BigDecimal(amt);
                        //判断订单金额是否小于电子会员卡的余额
                        if(balance !=null && orderAmt.compareTo(balance) < 0){
                            //判断是否有冻结的充值活动导致不够余额支付
                            electronicMembershipCardService.isNonpayment(payOrderInfo.getCustomerPhone(), stationInfo, orderAmt, balance);

                            //本次消费后的余额
                            ElectronicCardSubRes res = cardInfo.subtractAmount(orderAmt);
                            if (!res.isSuccess()) {
                                throw new CustomException(CodeMsg.BALANCE_NOT_EENOUGH);
                            }

                            BigDecimal newBalance = cardInfo.getTotalAmt();
                            //生成消费记录
                            electronicMembershipCardService.insetCardUseRecordConsumption(CustomerCardUseRecord.builder()
                                    .orderNo(ordNo)
                                    .customerNo(appUserInfo.getMemberCode())
                                    .amt(res.getAmt())
                                    .presentAmt(res.getPresentAmt())
                                    .status("1")
                                    .mobilePhone(cardInfo.getMobilePhone())
                                    .cardOilsType(cardInfo.getCardOilsType())
                                    .balance(newBalance)
                                    .stationId(stationId)
                                    .enterpriseId(enterpriseId)
                                    .usageType("-")
                                    .createTime(new Date())
                                    .build());
                            if(res.getPresentAmt().compareTo(BigDecimal.ZERO)>0){
                                presentAmountRecordService.createRecord(res.getPresentAmt(),PresentAmountRecord.businessName_payOrder,cardInfo.getMobilePhone(),ordNo,PresentAmountRecord.purpose_subtract,cardInfo.getId().longValue(),null);

                            }

                            //更新电子会员卡余额

                            CustomerElectronicCard.CustomerElectronicCardBuilder builder = CustomerElectronicCard.builder()
                                    .cardOilsType(cardType)
                                    .mobilePhone(appUserInfo.getMobilePhone())
                                    .recentlyTime(new Date())
                                    .amt(cardInfo.getAmt())
                                    .presentAmt(cardInfo.getPresentAmt());

                            if (StringUtils.equals("1",stationInfo.getEnterprise().getCardUseRangeFlag())) {
                                builder.stationId(stationInfo.getEnterpriseId());
                            }else{
                                builder.stationId2(stationInfo.getStationId());
                            }

                            electronicMembershipCardService.updateElectronicCardInfoByPhone(builder.build());
                            //更新立减活动的优惠余额
                            reductionActivityBalanceRecordService.updateBalance(cardType,appUserInfo.getUserId().longValue(),stationId.longValue(),enterpriseId.longValue(), payOrderInfo.getRechargeDiscountAmt(), orderAmt,appUserInfo.getMobilePhone());

                            //更新订单信息
                            BigDecimal discountAmt = new BigDecimal(receivableAmt).subtract(orderAmt); //电子卡优惠金额
                            payOrderService.getUpdatePayOrder(PayOrder.builder()
                                    .orderNo(ordNo)
                                    .status("1")
                                    .payType("dzk")
                                    .payDate(new Timestamp(new Date().getTime()))
                                    .receivableAmt(Double.valueOf(amt))
                                    .discountAmt(Double.valueOf(discountAmt.toString()))
                                    .amt(Double.valueOf(amt))
                                    .wxAmt(Double.valueOf("0"))
                                    .zfbAmt(Double.valueOf("0"))
                                    .dzkAmt(Double.valueOf(amt))
                                    .balance(newBalance)
                                    .actualRechargeAmt(res.getAmt())
                                    .build());


                            //消费返额
                            CalPresentAmt calPresentAmt = customerCardSettingDetailService.calConsumePresentAmtAndCreateRecord(payOrderInfo.getOrderNo(),
                                    payOrderInfo.getCustomerPhone(), BigDecimal.valueOf(payOrderInfo.getReceivableAmt()), BigDecimal.valueOf(payOrderInfo.getAmt()), payOrderInfo.getEnterpriseId().longValue(),
                                    payOrderInfo.getStationId().longValue(), "dzk_wx", cardInfo.getCardOilsType(), payOrderInfo.getOilGun(), payOrderInfo.getOilId(), PresentAmountRecord.businessName_payOrder, PresentAmountRecord.purpose_add);

                            if(calPresentAmt.getPresentAmt().compareTo(BigDecimal.ZERO)>0){
                                /*electronicMembershipCardService.insetCardUseRecordConsumption(CustomerCardUseRecord.builder()
                                        .orderNo(ordNo+"1")
                                        .customerNo(appUserInfo.getMemberCode())
                                        .presentAmt(calPresentAmt.getPresentAmt())
                                        .status("1")
                                        .mobilePhone(cardInfo.getMobilePhone())
                                        .cardOilsType(cardInfo.getCardOilsType())
                                        .balance(newBalance.add(calPresentAmt.getPresentAmt()))
                                        .stationId(stationId)
                                        .enterpriseId(enterpriseId)
                                        .usageType("+")
                                        .createTime(new Date())
                                        .payType("cs_pt")
                                        .build()
                                );*/
                            }



                            //计算积分
                            CalculateIntegral calResult = integralRuleService.calUserIntegral(CalculateIntegral.builder()
                                    .oilName(payOrderInfo.getOilName())
                                    .stationId(stationId)
                                    .enterpriseId(enterpriseId)
                                    .oilId(payOrderInfo.getOilId())
                                    .receivableAmt(new BigDecimal(payOrderInfo.getReceivableAmt().toString()))
                                    .oilLiters(new BigDecimal(payOrderInfo.getOrderLiters()))
                                    .amt(new BigDecimal(payOrderInfo.getAmt().toString()))
                                    .userId(payOrderInfo.getConsumerId())       //超级会员电子卡积分
                                    .build());
                            payOrderService.updateGrowthValueByOrdNo(calResult.getGrowValue().longValue(),ordNo);

                            appUserInfo.setIntegral(calResult.getIntegral() + appUserInfo.getIntegral());
                            appUserInfo.setGrowUpValue(calResult.getGrowValue() + appUserInfo.getGrowUpValue());
                            appUserInfoService.updateAppUserIntegral(appUserInfo);
                            //生成积分记录
                            calResult.setOrderNo(payOrderInfo.getOrderNo());
                            calResult.setNickName(appUserInfo.getBlogNickName());
                            calResult.setMobilePhone(appUserInfo.getMobilePhone());
                            integralRuleService.createIntegralRecord(calResult, "dzk",appUserInfo.getIntegral());

                            //根据油企是否开启优惠券功能，修改优惠券状态和主动领取优惠券
                            if(null != stationInfo.getEnterprise().getCouponEnabledFlag() && "1".equals(stationInfo.getEnterprise().getCouponEnabledFlag())){
                                //修改优惠券状态
                                if(StringUtils.isNotBlank(couponUserId)){
                                    logger.info("用户所用优惠券Id：" + couponUserId);
                                    Map<String, Object> param = new HashMap<>();
                                    param.put("couponUserId", couponUserId);
                                    List<CouponUser> couponUserList = couponService.selectCouponUserList(param);
                                    if(null != couponUserList && couponUserList.size() ==1){
                                        couponService.updateCouponUser(CouponUser.builder().verificationTime(new Date()).couponUserId(Integer.valueOf(couponUserId)).couponIsUsed("1").build());
                                        CouponTemplate ct = couponService.selectCouponTemInfoById(CouponTemplate.builder().couponTemplateId(couponUserList.get(0).getCouponTemplateId()).build());
                                        if(null != ct){
                                            couponService.updateCouponTemplate(CouponTemplate.builder()
                                                    .useCouponNum(ct.getUseCouponNum()+1)
                                                    .couponTemplateId(couponUserList.get(0).getCouponTemplateId())
                                                    .build());
                                        }
                                    }
                                }
                                int i = couponService.initiativeCoupon(appUserInfo, stationInfo.getStationId(), new BigDecimal(payOrderInfo.getReceivableAmt().toString()),ordNo);
                                //优惠券主动领取后推送消息
                                if(i>0)
                                    couponService.pushWxGzhInitiativeCouponInfo(stationInfo, payOrderInfo, i, appUserInfo);
                            }

                            resultData = ResultData.success(CodeMsg.SUCCESS);
                            //电子卡消费，与获得积分公众号通知
                            PayOrder newPayOrder =  payOrderService.selectOrderInfoByOrdNo(ordNo);
                            gzhNewsTemplateService.pushConsumeToUser(appUserInfo,newPayOrder,calResult.getIntegral());
                        }else {
                            resultData=ResultData.error(CodeMsg.BALANCE_NOT_EENOUGH);
                        }
                    }else {
                        resultData=ResultData.error(CodeMsg.USER_NOT_EXSIST);
                    }
                }else {
                    resultData=ResultData.error(CodeMsg.STATION_NOT_EXIST);
                }
            }else {
                resultData=ResultData.error(CodeMsg.NO_ORDER);
            }
        }else{
            resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    /*
     * 公众号电子卡充值 通联异步回调通知
     * @param request
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/getTLRechargePayCallback", consumes = "application/x-www-form-urlencoded", method = RequestMethod.POST)
    @Transactional
    public void getTLRechargePayCallback(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("通联支付接收到通知");
        request.setCharacterEncoding("UTF-8");//通知传输的编码为GBK
        response.setCharacterEncoding("UTF-8");
        TreeMap<String,String> params = getParams(request);//动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容
        logger.info("通联返回参数：" + params.toString());
        try {
            String ordNo = params.get("cusorderid");         //订单号
            String trxcode = params.get("trxcode");     //交易类型
            String amt = params.get("trxamt");       //交易金额
            logger.info("本次充值金额（单位：分）：" + amt);
            String transactionId = params.get("chnltrxid");
            CustomerCardUseRecord customerCardUseRecordInfo = electronicMembershipCardService.getCardRecordByOrderNo(CustomerCardUseRecord.builder().orderNo(ordNo).build());
            Station station = enterpriseService.selectStationById(customerCardUseRecordInfo.getStationId());
            Enterprise enterprise = station.getEnterprise();
            boolean cardUsingForAll = StringUtils.equals("1",enterprise.getCardUseRangeFlag());
            String payType = "VSP501".equals(trxcode) ? "wx" : "zfb";
            String appType = "wx".equals(payType) ? "1" : "2";
//            List<PayWay> payWayList = enterpriseService.selectStaPayWay(PayWay.builder()
//                    .stationId(customerCardUseRecordInfo.getStationId())
//                    .appType(appType)
//                    .useType("1").build());
//            String appkey = payWayList.get(0).getAllinpayRSAKey();
            boolean isSign = SybUtil.validSign(params, SybConstants.SYB_RSATLPUBKEY, SybConstants.SIGN_TYPE);         // 接受到推送通知,首先验签
            System.out.println("验签结果:"+isSign);
            //验签完毕进行业务处理
            if(isSign){
                //验签：
                logger.info("通联验签成功");
                //随行付回调验签成功更新客户电子卡余额 和 更新客户充值记录状态
                String payTime = params.get("paytime");
                // 0表示未支付  1表示已支付
                if(null != customerCardUseRecordInfo  && "0".equals(customerCardUseRecordInfo.getStatus())){
                    logger.info("充值单号：" + ordNo);
                    //查询客户该油品电子卡信息
                    //是否有赠送金额
                    BigDecimal presentAmt =BigDecimal.ZERO;
                    if(customerCardUseRecordInfo.getPresentAmt() !=null){
                        presentAmt = customerCardUseRecordInfo.getPresentAmt();  //客户充值赠送金额
                        logger.info("客户充值赠送金额：" +presentAmt.toString());
                    }

                    //获取客户充值的得电子卡信息
                    logger.info("用户手机号：" + customerCardUseRecordInfo.getMobilePhone() + "; 油企ID：" + station.getEnterpriseId() + "; 卡类型：" + customerCardUseRecordInfo.getCardOilsType());
                    AppUserInfo userinfo = new AppUserInfo();
                    userinfo.setMobilePhone(customerCardUseRecordInfo.getMobilePhone());
                    CustomerElectronicCard electronicCardInfo = electronicMembershipCardService.getAndCreateCustomerElectronicCard(userinfo,customerCardUseRecordInfo.getCardOilsType(), station);
                    if(electronicCardInfo !=null){
                        if(presentAmt.compareTo(BigDecimal.ZERO)>0){
                            //充值赠额记录
                            customerCardSettingDetailService.createRecord(presentAmt,PresentAmountRecord.businessName_customerCardUseRecord,customerCardUseRecordInfo.getMobilePhone(),ordNo,
                                    PresentAmountRecord.purpose_add,electronicCardInfo.getId().longValue(),customerCardUseRecordInfo.getCcsdId());
                        }

                        logger.info("客户当前原有金额：" + electronicCardInfo.getAmt().toString());
                        BigDecimal afterAmt = electronicCardInfo.getAmt().add(new BigDecimal(amt).multiply(DecimalConstant.O_01));
                        electronicCardInfo.setAmt(afterAmt);
                        BigDecimal afterPresentAmt = electronicCardInfo.getPresentAmt().add(presentAmt);
                        electronicCardInfo.setPresentAmt(afterPresentAmt);
                        //BigDecimal newBalance = electronicCardInfo.getAmt().add(new BigDecimal(amt).divide(new BigDecimal("100"))).add(presentAmt);   //客户新的余额
                        BigDecimal newBalance = electronicCardInfo.getTotalAmt();
                        //电子卡充值方式
                        String ccurPayType = "";
                        switch (payType){
                            case "WECHAT":
                                ccurPayType ="wx";
                                break;
                            case "ALIPAY":
                                ccurPayType ="zfb";
                                break;
                        }
                        if(StringUtils.isNotBlank(customerCardUseRecordInfo.getMobilePhone()) && null != customerCardUseRecordInfo.getStationId()){
                            //更新充值记录的状态和余额
                            electronicMembershipCardService.updateCardRecordStatusByOrderNo(CustomerCardUseRecord.builder()
                                    .payType(ccurPayType)
                                    .balance(newBalance)
                                    .transactionId(transactionId)
                                    .payTime(new SimpleDateFormat("yyyyMMddHHmmss").parse(payTime))
                                    .orderNo(ordNo)
                                    .status("1")
                                    .build());
                            //更新客户余额
                            CustomerElectronicCard.CustomerElectronicCardBuilder builder = CustomerElectronicCard.builder()
                                    .cardOilsType(customerCardUseRecordInfo.getCardOilsType())
                                    .mobilePhone(electronicCardInfo.getMobilePhone())
                                    .recentlyTime(new Date())
                                    .amt(afterAmt)
                                    .presentAmt(presentAmt);

                            if (cardUsingForAll) {
                                builder.stationId(station.getEnterpriseId());
                            }else{
                                builder.stationId2(station.getStationId());
                            }

                            electronicMembershipCardService.updateElectronicCardInfoByPhone(builder.build());
                            //更新参与立减活动的优惠余额
                            reductionActivityBalanceRecordService.createBalanceRecord(ordNo,customerCardUseRecordInfo.getCardOilsType(),new BigDecimal(amt).divide(new BigDecimal("100")),station,null,electronicCardInfo.getMobilePhone(),enterprise,"wx");
                            //充值活动发券
                            couponController.sendCounponByCardUserRecord(ordNo);
                            //充值活动送积分
                            Integral integral = electronicMembershipCardService.rechargeActivityGiveIntegral(ordNo);

                            logger.info("客户当前充值后应有金额：" + newBalance.toString());
                            logger.info("===========客户电子会员卡充值成功已到账====");
                            //获取要推送充值成功模板的ID
                            GzhNewsTemplate gzhNewsTemplateInfo = gzhNewsTemplateService.getGzhNewsTemplate(GzhNewsTemplate.builder()
                                    .stationId(station.getEnterpriseId())
                                    .templateType("3")      //3 代表电子会员卡充值成功模板类型
                                    .build());
                            if(gzhNewsTemplateInfo !=null && gzhNewsTemplateInfo.getTemplateId() !=null){
                                logger.info("当前要推送消息所用使用的模板ID："+ gzhNewsTemplateInfo.getTemplateId());
                                enterprise = enterpriseService.selectEnterpriseInfo(station.getEnterpriseId());
                                if(enterprise !=null && StringUtils.isNotBlank(enterprise.getGzhAppId()) && StringUtils.isNotBlank(enterprise.getGzhAppSecret())){
                                    String gzhAppId = enterprise.getGzhAppId();
                                    String gzhAppSecret = enterprise.getGzhAppSecret();
                                    //AppUserInfo appUserInfo = appUserInfoService.getAppUserInfo(AppUserInfo.builder().mobilePhone(customerCardUseRecordInfo.getMobilePhone()).stationId(station.getEnterpriseId()).build());
                                    if(StringUtils.isNotBlank(customerCardUseRecordInfo.getBlogOpenid())){

                                        String cardName = "";
                                        switch (customerCardUseRecordInfo.getCardOilsType()){
                                            case "0":
                                                cardName = "通用";
                                                break;
                                            case "1":
                                                cardName = "汽油";
                                                break;
                                            case "2":
                                                cardName = "柴油";
                                                break;
                                            case "3":
                                                cardName = "LNG";
                                                break;
                                            case "4":
                                                cardName = "CNG";
                                                break;
                                        }
//                                        List<WxMpTemplateData> wxMpTemplate = new ArrayList<>();
//                                        wxMpTemplate.add(new WxMpTemplateData("first","尊敬的"+customerCardUseRecordInfo.getCustomerName()+"，您好：\n" + "您在"+station.getStationName()+"的"+cardName+"电子卡充值成功信息如下"));
//                                        wxMpTemplate.add(new WxMpTemplateData("keyword1", electronicCardInfo.getCustomerNo()));
//                                        wxMpTemplate.add(new WxMpTemplateData("keyword2", amt + " 元"));
//                                        wxMpTemplate.add(new WxMpTemplateData("keyword3", presentAmt.toString()+ " 元"));
//                                        wxMpTemplate.add(new WxMpTemplateData("keyword4", newBalance.toString()+ " 元"));
//                                        wxMpTemplate.add(new WxMpTemplateData("keyword5", new SimpleDateFormat("yyyy年MM月dd日HH时mm分").format(new Date())));
//                                        wxMpTemplate.add(new WxMpTemplateData("remark","感谢您在"+ station.getStationName()+"的本次充值！"));
//                                        logger.info("要推送的消息内容：" +wxMpTemplate.toString());
//                                        wxPushUtil.push(gzhAppId, gzhAppSecret, gzhNewsTemplateInfo.getTemplateId(), customerCardUseRecordInfo.getBlogOpenid(), wxMpTemplate);

                                        //新修订
                                        String notifyName = station.getStationName() == null ? enterprise.getEnterpriseName() : station.getStationName();
                                        WxTemplateMsg wxTemplateMsg = new WxTemplateMsg();
                                        wxTemplateMsg.setTemplate_id(gzhNewsTemplateInfo.getTemplateId());
                                        wxTemplateMsg.setTouser(customerCardUseRecordInfo.getBlogOpenid());
                                        Map<String, WxTemplateData> templateDataMap = new HashMap<>();
                                        templateDataMap.put("first",      WxTemplateData.builder().value("尊敬的"+customerCardUseRecordInfo.getCustomerName()+"您好：" + "您在"+notifyName+"的"+cardName+"电子卡充值成功信息如下").build());
                                        templateDataMap.put("keyword1",   WxTemplateData.builder().value(electronicCardInfo.getCustomerNo()).build());
                                        templateDataMap.put("keyword2",   WxTemplateData.builder().value(new BigDecimal(amt).divide(new BigDecimal("100")).toString() + " 元").build());
                                        templateDataMap.put("keyword3",   WxTemplateData.builder().value(presentAmt.toString()+ " 元").build());
                                        templateDataMap.put("keyword4",   WxTemplateData.builder().value(newBalance.toString()+ " 元").build());
                                        templateDataMap.put("keyword5",   WxTemplateData.builder().value(new SimpleDateFormat("yyyy年MM月dd日HH时mm分").format(new Date())).build());
                                        templateDataMap.put("remark",     WxTemplateData.builder().value("感谢您在"+ notifyName+"的本次充值！").build());
                                        wxTemplateMsg.setData(templateDataMap);
                                        wxPushUtil.sendTemplateMsg(gzhAppId, gzhAppSecret, wxTemplateMsg);
                                        logger.info("===================================本次电子卡充值流程结束===========================================");
                                    }
                                }
                            }
                        }else {
                            logger.info("么有手机号和油站ID");
                        }
                    }
                }
            }else {
                logger.info("验签失败");
            }
        } catch (Exception e) {//处理异常
            e.printStackTrace();
        }
        finally{//收到通知,返回success
            response.getOutputStream().write("success".getBytes());
            response.flushBuffer();
        }
    }

    /**
     * 通联 动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容由于收银宝加字段而引起的签名异常
     * @param request
     * @return
     */
    private TreeMap<String, String> getParams(HttpServletRequest request){
        TreeMap<String, String> map = new TreeMap<String, String>();
        Map reqMap = request.getParameterMap();
        for(Object key:reqMap.keySet()){
            String value = ((String[])reqMap.get(key))[0];
            //System.out.println(key+";"+value);
            map.put(key.toString(),value);
        }
        return map;
    }


    //用户电子会员卡（储蓄卡）充值功能随行付回调功能
    @RequestMapping(value = "/getCardRechargeCallback", consumes = "application/json", method = RequestMethod.POST)
    public JSONObject getCardRechargeCallback(@RequestBody JSONObject request) throws ParseException {
        logger.info("=========================电子会员卡（储蓄卡）充值功能随行付回调功能===============================");
        logger.info("电子会员卡（储蓄卡）充值功能随行付回调返回过来的参数："+request);
        //logger.info("ordNo信息：" + request.get("ordNo").toString());
        //logger.info("sign信息：" + request.get("sign").toString());
//        Gson gson =new Gson();
//        String sxfUuid=request.get("sxfUuid").toString();     //随行付落单号
//        String payWay=request.get("payWay").toString();     //随行付交易方式
        String payTime=request.getString("payTime");   //随行付交易时间
//        String uuid=request.get("uuid").toString();         //随行付交易流水号
//        String mno=request.get("mno").toString();//发起交易的商户编号
        String ordNo=request.getString("ordNo");//商户生成的订单号
        String amt=request.getString("amt");//金额
//        String buyerId=request.get("buyerId").toString();//用户登录
        String transactionId=request.getString("transactionId");//用户登录
//        String drType=request.get("drType").toString();//借贷记标识 1-借,2-贷，3-其他
        String payType=request.getString("payType");//对订单的描述，取值范围：WECHAT:微信,ALIPAY:支付宝,UNIONPAY:
//        String payBank=request.get("payBank").toString();//付款银行银行编码，例如 ICBC
//        String pointAmount=request.get("pointAmount").toString();//代金券金额
//        String totalOffstAmt=request.get("totalOffstAmt").toString();//消 费 者 付 款金额
//        String settleAmt=request.get("settleAmt").toString();//商家入账金额
//        String timeStamp=request.get("timeStamp").toString();//响应时间
//        String sign=request.get("sign").toString();//签名
//        String bizCode=request.get("bizCode").toString();//业务返回码
//        String bizMsg=request.get("bizMsg").toString();//业 务 返 回 信息
//        String openid=request.get("openid").toString();//微 信 或 支 付宝身份id()opendid userid
//        String channelId=request.get("channelId").toString();//渠道商户号
//        String subMechId=request.get("subMechId").toString();//子商户号
//        String finishTime=request.get("finishTime").toString();//交易完成时间
//        String clearDt=request.get("clearDt").toString();
//        String settlementBatchNo=request.get("settlementBatchNo").toString();
        //String origOrdNo=request.get("origOrdNo").toString();//反交易退款异步通知
        //String origUuid=request.get("origUuid").toString();//token
        //String scene=request.get("scene").toString();//用户登录
        //String buyerAccount=request.get("buyerAccount").toString();//
        //String realRefundAmount=request.get("realRefundAmount").toString();//商家出账金额
        //String recFeeAmt=request.get("recFeeAmt").toString();//交易手续费
        //String recFeeRate=request.get("recFeeRate").toString();//交易手续费率
        //String refBuyerAmt=request.get("refBuyerAmt").toString();//消 费 者 到 账金额
        String extend =request.containsKey("extend") ? request.getString("extend") : null;//备用

        //将业务参数存放在 JSON 对象中
//        JSONObject reqData = new JSONObject();
//
//        //支付场景
//        if(request.containsKey("scene") && request.get("scene") !=null){
//            String scene = request.get("scene").toString();
//            reqData.put("scene", scene);
//        }
//
//        //recFeeRate
//        if(request.containsKey("recFeeRate") && request.get("recFeeRate") !=null){
//            String recFeeRate = request.get("recFeeRate").toString();
//            reqData.put("recFeeRate", recFeeRate);
//        }
//
//        //消 费 者 到 账金额
//        if(request.containsKey("refBuyerAmt") && request.get("refBuyerAmt") !=null){
//            String refBuyerAmt = request.get("refBuyerAmt").toString();
//            reqData.put("refBuyerAmt", refBuyerAmt);
//        }
//
//        //buyerAccount 支付宝买家登录账号  掩码；示例：135***1234
//        if(request.containsKey("buyerAccount") && request.get("buyerAccount") !=null){
//            String buyerAccount = request.get("buyerAccount").toString();
//            reqData.put("buyerAccount", buyerAccount);
//        }
//
//        //备用
//        if(request.containsKey("extend") && request.get("extend") !=null){
//            String extend1 = request.get("extend").toString();
//            reqData.put("extend", extend1);
//        }
//        //优惠券参数
//        if(request.containsKey("promotionDetail") && request.get("promotionDetail") !=null){
//            String promotionDetail = request.get("promotionDetail").toString();
//            reqData.put("promotionDetail", promotionDetail);
//        }
//        //商家出账金额
//        if(request.containsKey("realRefundAmount") && request.get("realRefundAmount") !=null){
//            String realRefundAmount = request.get("realRefundAmount").toString();
//            reqData.put("realRefundAmount", realRefundAmount);
//        }
//        //szltFlag
//        if(request.containsKey("szltFlag") && request.get("szltFlag") !=null){
//            String szltFlag = request.get("szltFlag").toString();
//            reqData.put("szltFlag", szltFlag);
//        }
//        //recFeeAmt
//        if(request.containsKey("recFeeAmt") && request.get("recFeeAmt") !=null){
//            String recFeeAmt = request.get("recFeeAmt").toString();
//            reqData.put("recFeeAmt", recFeeAmt);
//        }
//        //szltRecfeeAmt
//        if(request.containsKey("szltRecfeeAmt") && request.get("szltRecfeeAmt") !=null){
//            String szltRecfeeAmt = request.get("szltRecfeeAmt").toString();
//            reqData.put("szltRecfeeAmt", szltRecfeeAmt);
//        }
//
//        reqData.put("sxfUuid",sxfUuid);
//        reqData.put("payWay",payWay);
//        reqData.put("payTime",payTime);
//        reqData.put("uuid",uuid);
//        reqData.put("mno",mno);
//        reqData.put("ordNo",ordNo);
//        reqData.put("amt",amt);
//        reqData.put("buyerId",buyerId);
//        reqData.put("transactionId",transactionId);
//        reqData.put("drType",drType);
//        reqData.put("payType",payType);
//        reqData.put("payBank",payBank);
//        reqData.put("pointAmount",pointAmount);
//        reqData.put("totalOffstAmt",totalOffstAmt);
//        reqData.put("settleAmt",settleAmt);
//        reqData.put("timeStamp",timeStamp);
//        reqData.put("bizCode",bizCode);
//        reqData.put("bizMsg",bizMsg);
//        reqData.put("openid",openid);
//        reqData.put("channelId",channelId);
//        reqData.put("subMechId",subMechId);
//        reqData.put("finishTime",finishTime);
//        reqData.put("clearDt",clearDt);
//        reqData.put("settlementBatchNo",settlementBatchNo);
        //reqData.put("realRefundAmount",realRefundAmount);
        //reqData.put("recFeeAmt",recFeeAmt);
        //reqData.put("recFeeRate",recFeeRate);
        //reqData.put("buyerAccount",buyerAccount);
        //reqData.put("origOrdNo",origOrdNo);
        //reqData.put("origUuid",origUuid);
        //reqData.put("scene",scene);
        //reqData.put("refBuyerAmt",refBuyerAmt);
        //reqData.put("extend",extend);
        //根据回调信息，先进行验签，验签后修改状态
//        logger.info("打印参数信息"+gson.toJson(reqData));
        //不要对reqData排序 所以用LinkedHashMap
//        HashMap<String, Object> result = JSON.parseObject(gson.toJson(reqData), LinkedHashMap.class, Feature.OrderedField);
        //验签
        // 先不验签
//        String resultStr = RSASignature.getOrderContent(result);
        //JSONObject req = new JSONObject();
        //System.out.println(resultStr);
        JSONObject req = new JSONObject();
//        if (RSASignature.doCheck(resultStr, sign, SXFPaySign.sxfPublic)) {
            req.put("code","success");
            req.put("msg","成功");
            logger.info("验签成功");
            String savedPayType = null;
            Integer preId = null;
        if (StringUtils.isNotBlank(extend)) {
            JSONObject extendObj = JSONObject.parseObject(extend);
            savedPayType = extendObj.getString("payType");
            preId = extendObj.getInteger("pId");
        }
        electronicMembershipCardService.sxfDzkRechargeCallback(payTime, ordNo, amt, transactionId, payType,savedPayType,preId);
//        }else {
//            logger.info("验签失败");
//            req.put("code","fail");
//            req.put("msg","失败");
//        }
        logger.info("返回随行付参数信息："+req.toString());
        return req;
    }
    /***
     * 公众号 云闪付扫呗  用户电子会员卡（储蓄卡）充值功能支付回调
     * @param params
     * @return
     */
    @RequestMapping(value = "/getYunPayGzhCallback", consumes = "text/xml", method = RequestMethod.POST)
    @Transactional
    public net.sf.json.JSONObject getYunPayGzhCallback(@RequestBody String params){
        net.sf.json.JSONObject result = new net.sf.json.JSONObject();       //返回给扫呗状态码
        logger.info("=============================云闪付（扫呗）公众号电子卡充值 回调接口 ** 开始 ** ===============================================");
        YunPayCallBack yunPayCallBack = JSON.parseObject(params, YunPayCallBack.class);
        logger.info("云闪付扫呗 公众号支付 回调接口返回参数：" + params);System.out.println("扫呗调用回调接口返回参数：" + params);
        if(yunPayCallBack.getResult_code() !=null && yunPayCallBack.getResult_code().equals("01")){
            logger.info("  -------------------------云闪付回调成功--------------------------  ");
            //返给云闪付状态码
            result.put("return_code", "01");
            result.put("return_msg", "success");
            //业务逻辑
            String ordNo = yunPayCallBack.getTerminal_trace();
            String amt = String.valueOf(new BigDecimal(yunPayCallBack.getTotal_fee()).divide(new BigDecimal("100")));
            CustomerCardUseRecord customerCardUseRecordInfo = electronicMembershipCardService.getCardRecordByOrderNo(CustomerCardUseRecord.builder().orderNo(ordNo).build());
            // 0表示未支付  1表示已支付
            if(customerCardUseRecordInfo !=null && customerCardUseRecordInfo.getStatus().equals("0")){
                logger.info("充值单号：" + ordNo);
                Station station = enterpriseService.selectStationById(customerCardUseRecordInfo.getStationId());
                Enterprise enterprise = station.getEnterprise();
                boolean cardUsingForAll = StringUtils.equals("1",enterprise.getCardUseRangeFlag());
                //是否有赠送金额
                BigDecimal presentAmt =BigDecimal.ZERO;
                if(customerCardUseRecordInfo.getPresentAmt() !=null){
                    presentAmt = customerCardUseRecordInfo.getPresentAmt();  //客户充值赠送金额
                    logger.info("客户充值赠送金额：" +presentAmt.toString());
                }
                //获取客户充值的得电子卡信息
                AppUserInfo userinfo = new AppUserInfo();
                userinfo.setMobilePhone(customerCardUseRecordInfo.getMobilePhone());
                CustomerElectronicCard electronicCardInfo = electronicMembershipCardService.getAndCreateCustomerElectronicCard(userinfo,customerCardUseRecordInfo.getCardOilsType(), station);
                if(electronicCardInfo !=null){
                    if(presentAmt.compareTo(BigDecimal.ZERO)>0){
                        //充值赠额记录
                        customerCardSettingDetailService.createRecord(presentAmt,PresentAmountRecord.businessName_customerCardUseRecord,customerCardUseRecordInfo.getMobilePhone(),ordNo,
                                PresentAmountRecord.purpose_add,electronicCardInfo.getId().longValue(),customerCardUseRecordInfo.getCcsdId());
                    }

                    logger.info("客户当前原有金额：" + electronicCardInfo.getAmt().toString());
                    //新的余额
                    BigDecimal afterAmt = electronicCardInfo.getAmt().add(new BigDecimal(amt));
                    electronicCardInfo.setAmt(afterAmt);
                    BigDecimal afterPresentAmt = electronicCardInfo.getPresentAmt().add(presentAmt);
                    electronicCardInfo.setPresentAmt(afterPresentAmt);
                    //BigDecimal newBalance = electronicCardInfo.getAmt().add(new BigDecimal(amt)).add(presentAmt);   //客户新的余额
                    BigDecimal newBalance = electronicCardInfo.getTotalAmt();
                    String ccurPayType = "";
                    switch (yunPayCallBack.getPay_type()){
                        case "010":
                            ccurPayType ="wx";
                            break;
                        case "020":
                            ccurPayType ="zfb";
                            break;
                    }
                    if(StringUtils.isNotBlank(customerCardUseRecordInfo.getMobilePhone()) && null !=customerCardUseRecordInfo.getStationId()){
                        //更新充值记录的状态和余额
                        electronicMembershipCardService.updateCardRecordStatusByOrderNo(CustomerCardUseRecord.builder()
                                .mobilePhone(electronicCardInfo.getMobilePhone())
                                .transactionId(yunPayCallBack.getChannel_trade_no())
                                .orderNo(ordNo)
                                .status("1")
                                .balance(newBalance)
                                .payType(ccurPayType)
                                .build());
                        //更新客户余额
                        CustomerElectronicCard.CustomerElectronicCardBuilder builder = CustomerElectronicCard.builder()
                                .cardOilsType(customerCardUseRecordInfo.getCardOilsType())
                                .mobilePhone(electronicCardInfo.getMobilePhone())
                                .recentlyTime(new Date())
                                .amt(afterAmt)
                                .presentAmt(afterPresentAmt);

                        if (cardUsingForAll) {
                            builder.stationId(station.getEnterpriseId());
                        }else{
                            builder.stationId2(station.getStationId());
                        }

                        electronicMembershipCardService.updateElectronicCardInfoByPhone(builder.build());
                        //更新参与立减活动的优惠余额
                        reductionActivityBalanceRecordService.createBalanceRecord(ordNo,customerCardUseRecordInfo.getCardOilsType(),new BigDecimal(amt),station,null,electronicCardInfo.getMobilePhone(),enterprise,"wx");

                        //充值活动发券
                        couponController.sendCounponByCardUserRecord(ordNo);
                        //充值活动送积分
                        Integral integral = electronicMembershipCardService.rechargeActivityGiveIntegral(ordNo);

                        logger.info("客户充值后余额：" + newBalance);
                        logger.info("===========客户电子会员卡充值成功已到账====");
                        //String stationName = customerCardUseRecordInfo.getStationName();
                        String customerNo = electronicCardInfo.getCustomerNo();     //电子卡号
                        //获取要推送充值成功模板的ID
                        GzhNewsTemplate gzhNewsTemplate = new GzhNewsTemplate();
                        gzhNewsTemplate.setTemplateType("3");   //3 代表电子会员卡充值成功模板类型
                        gzhNewsTemplate.setStationId(station.getEnterpriseId());
                        GzhNewsTemplate gzhNewsTemplateInfo = gzhNewsTemplateService.getGzhNewsTemplate(gzhNewsTemplate);
                        if(gzhNewsTemplateInfo !=null && gzhNewsTemplateInfo.getTemplateId() !=null){
                            logger.info("当前要推送消息所用使用的模板ID："+ gzhNewsTemplateInfo.getTemplateId());
                            enterprise = enterpriseService.selectEnterpriseInfo(station.getEnterpriseId());
                            if(enterprise !=null && StringUtils.isNotBlank(enterprise.getGzhAppId()) && StringUtils.isNotBlank(enterprise.getGzhAppSecret())){
                                String gzhAppId = enterprise.getGzhAppId();
                                String gzhAppSecret = enterprise.getGzhAppSecret();
                                //AppUserInfo appUserInfo = appUserInfoService.getAppUserInfo(AppUserInfo.builder().mobilePhone(customerCardUseRecordInfo.getMobilePhone()).stationId(station.getEnterpriseId()).build());
                                if(StringUtils.isNotBlank(customerCardUseRecordInfo.getBlogOpenid())){
                                    //List<WxMpTemplateData> wxMpTemplate = new ArrayList<>();
                                    String cardName ="";
                                    switch (customerCardUseRecordInfo.getCardOilsType()){
                                        case "0":
                                            cardName = "通用";
                                            break;
                                        case "1":
                                            cardName = "汽油";
                                            break;
                                        case "2":
                                            cardName = "柴油";
                                            break;
                                        case "3":
                                            cardName = "LNG";
                                            break;
                                        case "4":
                                            cardName = "CNG";
                                            break;
                                    }
//                                    wxMpTemplate.add(new WxMpTemplateData("first","尊敬的"+customerCardUseRecordInfo.getCustomerName()+"，您好：\n" + "您在"+stationName+"的"+cardName+"电子卡充值成功信息如下"));
//                                    wxMpTemplate.add(new WxMpTemplateData("keyword1", customerNo));
//                                    wxMpTemplate.add(new WxMpTemplateData("keyword2", amt + " 元"));
//                                    wxMpTemplate.add(new WxMpTemplateData("keyword3", presentAmt.toString()+ " 元"));
//                                    wxMpTemplate.add(new WxMpTemplateData("keyword4", newBalance.toString()+ " 元"));
//                                    wxMpTemplate.add(new WxMpTemplateData("keyword5", new SimpleDateFormat("yyyy年MM月dd日HH时mm分").format(new Date())));
//                                    wxMpTemplate.add(new WxMpTemplateData("remark","感谢您在"+ stationName+"的本次充值！"));
//                                    logger.info("要推送的消息内容：" +wxMpTemplate.toString());
//                                    wxPushUtil.push(gzhAppId, gzhAppSecret, gzhNewsTemplateInfo.getTemplateId(), customerCardUseRecordInfo.getBlogOpenid(), wxMpTemplate);
                                    //logger.info("结束微信公众号电子会员卡消息推送成功，推送人："+ appUserInfos.getBlogOpenid());

                                    //新修订
                                    String notifyName = station.getStationName() == null ? enterprise.getEnterpriseName() : station.getStationName();
                                    WxTemplateMsg wxTemplateMsg = new WxTemplateMsg();
                                    wxTemplateMsg.setTemplate_id(gzhNewsTemplateInfo.getTemplateId());
                                    wxTemplateMsg.setTouser(customerCardUseRecordInfo.getBlogOpenid());
                                    Map<String, WxTemplateData> templateDataMap = new HashMap<>();
                                    templateDataMap.put("first",      WxTemplateData.builder().value("尊敬的"+customerCardUseRecordInfo.getCustomerName()+"您好：" + "您在"+notifyName+"的"+cardName+"电子卡充值成功信息如下").build());
                                    templateDataMap.put("keyword1",   WxTemplateData.builder().value(customerNo).build());
                                    templateDataMap.put("keyword2",   WxTemplateData.builder().value(amt + " 元").build());
                                    templateDataMap.put("keyword3",   WxTemplateData.builder().value(presentAmt.toString()+ " 元").build());
                                    templateDataMap.put("keyword4",   WxTemplateData.builder().value(newBalance.toString()+ " 元").build());
                                    templateDataMap.put("keyword5",   WxTemplateData.builder().value(new SimpleDateFormat("yyyy年MM月dd日HH时mm分").format(new Date())).build());
                                    templateDataMap.put("remark",     WxTemplateData.builder().value("感谢您在"+ notifyName+"的本次充值！").build());
                                    wxTemplateMsg.setData(templateDataMap);
                                    wxPushUtil.sendTemplateMsg(gzhAppId, gzhAppSecret, wxTemplateMsg);
                                }
                            }
                        }
                    }else {
                        logger.info("无手机号或油企ID");
                    }
                }
            }else {
                logger.info("此充值订单: "+ordNo+" 不存在或已完成支付！");
            }
        }else {
            result.put("return_code", "02");
            result.put("return_msg", "fail");
        }
        logger.info("返给云闪付结果信息：" + result);
        logger.info("=======================================云闪付（扫呗） 公众号电子卡充值支付 回调接口 ** 结束 ** ===============================================");
        return result;
    }

    //获取用户电子会员卡（储蓄卡）充值消费记录
    @RequestMapping(value = "/getCardRecordList", method = RequestMethod.GET)
    @ApiOperation(value = "获取用户电子会员卡（储蓄卡）充值消费记录", httpMethod = "GET", notes = "获取用户电子会员卡（储蓄卡）充值消费记录")
    public String getCardRecordList(@ApiParam(value = "油企ID", required = true) @RequestParam Integer enterpriseId,
                                    @ApiParam(value = "用户mobilePhone", required = true) @RequestParam String mobilePhone, String usageType,
                                    @RequestParam Integer pageSize,
                                    @RequestParam Integer pageNum, String cardOilsType){
        Gson gson =new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        //返回结果集
        ResultData resultData = null;
        if(enterpriseId !=null && StringUtils.isNotBlank(mobilePhone) && pageSize !=null && pageNum !=null){
            switch (usageType){
                case "0":
                    usageType ="-"; // '0' 代表消费  '1' 代表充值
                    break;
                case "1":
                    usageType ="+";
                    break;
            }
            PageHelper.startPage(pageNum, pageSize);
            List<CustomerCardUseRecord> cardUseRecordList = electronicMembershipCardService.getCardUseRecordList(CustomerCardUseRecord.builder()
                    .usageType(usageType)
                    .cardOilsType(cardOilsType)
                    .enterpriseId(enterpriseId)
                    .mobilePhone(mobilePhone).build());
           /* cardUseRecordList = cardUseRecordList.stream().filter(c -> (StringUtils.isNotEmpty(c.getPayType()) && !c.getPayType().equals("cs_pt")) ||
                    StringUtils.isEmpty(c.getPayType())).collect(Collectors.toList());*/
            resultData = ResultData.success(new PageInfo(cardUseRecordList));
        }else {
            resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    //获取用户电子会员卡（储蓄卡）充值消费记录详情
    @RequestMapping(value = "/getCardRecordDetail", method = RequestMethod.GET)
    @ApiOperation(value = "获取用户电子会员卡（储蓄卡）充值消费记录详情", httpMethod = "GET", notes = "获取用户电子会员卡（储蓄卡）充值消费记录详情")
    public String getCardRecordDetail(@RequestParam String orderNo,@RequestParam String cardOilsType){
        ResultData resultData = null;
        Gson gson =new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        if(StringUtils.isEmpty(orderNo)||StringUtils.isEmpty(cardOilsType)){
            resultData = ResultData.error("orderNo和cardOilsType不能为空");
            return gson.toJson(resultData);
        }

        List<CustomerCardUseRecord> cardUseRecordList = electronicMembershipCardService.getCardUseRecordList(CustomerCardUseRecord.builder()
                .orderNo(orderNo)
                .cardOilsType(cardOilsType).build());
        CustomerCardUseRecord useRecord = cardUseRecordList.get(0);
        if(useRecord==null){
            useRecord=new CustomerCardUseRecord();
        }
        resultData = ResultData.success(useRecord);
        return gson.toJson(resultData);
    }

    //查询油站电子会员卡（储蓄卡）充值设置规则
    @RequestMapping(value = "/getCardRechargeSettingList", method = RequestMethod.GET)
    @ApiOperation(value = "查询油站电子会员卡（储蓄卡）充值设置规则", httpMethod = "GET", notes = "查询油站电子会员卡（储蓄卡）充值设置规则")
    public String getCardRechargeSettingList(@ApiParam(value = "油企ID", required = true) @RequestParam Integer enterpriseId, @RequestParam Integer stationId,String cardOilsType){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(enterpriseId !=null){
            List<CustomerCardSetting> cardRechargeSettingList = electronicMembershipCardService.getCardRechargeSettingList(CustomerCardSetting.builder()
                    .stationId(stationId)
                    .enterpriseId(enterpriseId)
                    .cardOilsType(cardOilsType)
                    .orderBy("ASC")
                    .delFlag("0").build());
            resultData = ResultData.success(cardRechargeSettingList);
        }else {
            resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }
    //查询油站电子会员卡（储蓄卡）充值设置规则
    @RequestMapping(value = "/getCardRechargeMinAmt", method = RequestMethod.GET)
    @ApiOperation(value = "查询电子卡最低充值金额", httpMethod = "GET", notes = "查询油站电子会员卡（储蓄卡）充值设置规则")
    public String getCardRechargeMinAmt(@ApiParam(value = "油企ID", required = true) @RequestParam Integer enterpriseId){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(enterpriseId !=null){
            List<CustomerCardSetting> cardRechargeSettingList = electronicMembershipCardService.getCardRechargeMinAmt(CustomerCardSetting.builder()
                    .stationId(enterpriseId)
                    .delFlag("0").build());
            resultData = ResultData.success(cardRechargeSettingList);
        }else {
            resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    @GetMapping("/electronicCard/getRechargePrivilegeList")
    @ApiOperation(value = "获取充值优惠信息")
    public ResultData<List<RechargePrivilegeVO>> getRechargePrivilegeList(@RequestParam Long stationId,
                                                                          @RequestParam String cardType){
        return ResultData.success(customerCardSettingDetailService.getStationRechargePrivilegeList(stationId,cardType));
    }

    /**
     * 查询客户电子卡交易记录列表
     */
    @GetMapping("/getCardRecordListNew")
    @ApiOperation(value = "查询客户电子卡交易记录列表", httpMethod = "GET")
    public String getCardRecordListNew(@ApiParam(value = "油企ID", required = true) @RequestParam Integer enterpriseId,
                                       @ApiParam(value = "用户mobilePhone", required = true) @RequestParam String mobilePhone, @ApiParam(value = "交易类型", required = false) @RequestParam String usageType, @RequestParam Integer pageSize,
                                       @RequestParam Integer pageNum) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

        //返回结果集
        ResultData resultData = null;
        if (enterpriseId != null && StringUtils.isNotBlank(mobilePhone) && pageSize != null && pageNum != null) {
            Enterprise enterprise = enterpriseService.selectEnterpriseInfo(enterpriseId);
            if (null == enterprise) {
                throw new CustomException("[" + enterpriseId + "]对应的油企不存在");
            }
            String payType = null;
            // '0' 代表消费  '1' 代表充值
            switch (usageType) {
                case "0":
                    usageType = "-";
                    payType = "out";
                    break;
                case "1":
                    usageType = "+";
                    break;
            }
            PageHelper.startPage(pageNum, pageSize);
            List<CustomerCardUseRecord> cardUseRecordList = electronicMembershipCardService.selectCustomerCardUseRecords(CustomerCardUseRecord.builder()
                    .usageType(usageType)
                    .enterpriseId(enterpriseId)
                    .mobilePhone(mobilePhone)
                    .payType(payType).build());
            resultData = ResultData.success(new PageInfo(cardUseRecordList));
        } else {
            resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

}
